如何在从指令创建组件实例时运行ngAfterViewInit()?

时间:2017-04-27 08:18:26

标签: angular angular2-directives angular2-components

我有一个指令,即在代码中创建他使用的组件模板的实例并设置其innerHTml,这将改变tempalte维度:

  var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
  this.templateComponent = this.viewContainerRef.createComponent(factory);

  this.templateComponent.instance.htmlStr = anyText;

现在,这是问题所在。在这个阶段,我将不确定组件大小:

console.log(this.templateComponent.instance.width);    //undefined
console.log(this.templateComponent.instance.height);   //undefined

在调试中我注意到只有在我的组件运行 ngAfterViewInit()之后,才能从我的指令中读取组件模板的宽度和高度并使用它们。

有没有办法告诉我的指令要等到 ngAfterViewInit()结束, 而不是从我的指令中得到我需要的信息。

2 个答案:

答案 0 :(得分:3)

constructor(private cdRef:ChangeDetectorRef) {}

...

  var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
  this.templateComponent = this.viewContainerRef.createComponent(factory);
  this.templateComponent.instance.htmlStr = anyText;

  this.cdRef.detectChanges(); // run change detection immediately

  console.log(this.templateComponent.instance.width);    //undefined
  console.log(this.templateComponent.instance.height);   //undefined

答案 1 :(得分:0)

使用全局注入的ChangeDetectorRef是不必要的,并且可能不起作用。您可以依靠ComponentRef的{​​{1}}方法:

changeDetectorRef
相关问题