【发布时间】:2017-03-29 09:36:16
【问题描述】:
在动态组件加载的情况下不调用 ngOnChanges 生命周期钩子是预期的行为吗? 只为我调用了构造函数 ngOnInit 和 ngAfterViewInit。但是根据docs 应该在ngOnInit 之前调用它。
我正在加载这样的组件:
@ViewChild('place', { read: ViewContainerRef }) container: ViewContainerRef;
private componentRef: ComponentRef<MyLoggerComponent>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(MyLoggerComponent);
this.componentRef = this.container.createComponent(componentFactory);
this.componentRef.changeDetectorRef.detectChanges();
}
【问题讨论】:
-
ngOnChanges() 仅在 Angular 绑定更新输入且动态创建的组件不支持 @Input() 或 @Output() 时调用
-
如果常规组件具有@Input 属性并且它已更新,它将触发 ngOnchange 此 plunker 将无法工作 plnkr.co/edit/w2Cc1ssw30ZcP0M2gFdJ?p=preview
-
这是带有常规组件的工作 plunker plnkr.co/edit/sFl84z0XY6OpCa5imTvz?p=preview
标签: angular