我有一个指令,即在代码中创建他使用的组件模板的实例并设置其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()结束, 而不是从我的指令中得到我需要的信息。
答案 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