Angular 2动态组件加载ngOnChanges生命周期钩子调用

时间:2016-11-15 13:23:37

标签: angular

在动态组件加载的情况下,是否预期行为不会调用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();
   }

Plunker

1 个答案:

答案 0 :(得分:8)

根据讨论https://github.com/angular/angular/issues/8903,即使在调用ngOnChanges之后,动态组件加载也不应在子组件中触发detectChanges,因为此事件仅保留用于模板绑定。

如果您的子组件仅以动态方式加载,则可以使用Javascript setter而不是ngOnChanges。这是一个例子:

export class DynamicallyLoadedComponent {
  private _property: string;
  get property(): string { return this._property; }
  set property(newVal: string) {
    if (this._property === newVal) { return; }
    this._property = newVal;

    this.onChanges();  // instead of ngOnChanges
  }
}