Ang*_*One 5 angular2-directives angular2-components angular
我有一个指令,它在代码中创建一个他使用的组件模板实例并设置它的innerHTml,这将改变模板维度:
var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
this.templateComponent = this.viewContainerRef.createComponent(factory);
this.templateComponent.instance.htmlStr = anyText;
Run Code Online (Sandbox Code Playgroud)
现在,问题来了。在这个阶段,我将获得未定义的组件尺寸:
console.log(this.templateComponent.instance.width); //undefined
console.log(this.templateComponent.instance.height); //undefined
Run Code Online (Sandbox Code Playgroud)
在调试中,我注意到只有在我的组件运行ngAfterViewInit()之后,我才能从指令中读取组件模板的宽度和高度并使用该值。
有没有一种方法可以告诉我的指令等到ngAfterViewInit()结束,然后用我正在寻找的信息从指令中执行我需要的操作。
使用全局注入ChangeDetectorRef不是必需的,也可能不起作用。您可以信赖 的ComponentRef方法changeDetectorRef:
var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
this.templateComponent = this.viewContainerRef.createComponent(factory);
this.templateComponent.instance.htmlStr = anyText;
this.templateComponent.changeDetectorRef.detectChanges();
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1386 次 |
| 最近记录: |