通过组件引用

时间:2017-01-30 17:19:32

标签: angularjs dynamic ngonchanges

我正在以这种方式动态创建组件:

let componentFactory = this._componentFactoryResolver.resolveComponentFactory(this.component);
this.componentRef = this.viewContainerRef.createComponent(componentFactory);
this.componentRef.instance.text = this.text;

如您所见,我还为“text”属性赋值。这项工作,但它不会触发目标组件中的ngOnChanges,因此也不会触发更改检测(我正在使用“推送”策略)。

我尝试用

手动触发它
this.componentRef.changeDetectorRef.detectChanges();

this.componentRef.changeDetectorRef.markForCheck();

但没有成功。

如何以更好的方式将新文本值分配给目标组件@Input('text')? Text只是一个String值。

更新 我现在已经在目标组件中使用setter构建了一个解决方法:

@Input('text')
set text(text: string) {
    this._text = text;
    this.cdRef.markForCheck();
}

它有效,但有点hacky,我仍然更喜欢更“有角度”的方式。

0 个答案:

没有答案