我有一个Angular 2应用程序,我需要动态创建子组件。
是否必须致电' detectChanges()'和' 分离()'组件引用变量的方法' componentRef.changeDetectorRef' ?
即使我不使用它们,我也认为事情正常。
这些方法实际上是指组件注入性能改进吗?
@Component({
selector: 'container',
template: '<template #content></template>'
})
export class ContainerComponet implements AfterViewInit {
contentComponentRef:any;
@ViewChild('content', {read: ViewContainerRef}) contentHandle;
constructor(private componentResolver:ComponentResolver) {
super();
}
ngAfterViewInit() {
if (this.contentComponentRef)
this.contentComponentRef.destroy();
this.componentResolver.resolveComponent(ChildComponent)
.then((factory:ComponentFactory<any>) => {
let componentRef = this.contentHandle.createComponent(factory);
componentRef.instance['child_component_property'] = 'dummy value for child';
componentRef.changeDetectorRef.detectChanges();
componentRef.onDestroy(() => {
componentRef.changeDetectorRef.detach();
});
this.contentComponentRef = componentRef;
return componentRef;
});
}
}