fjozsef
fjozsef

Reputation: 135

Angular 2 Dynamic Component loading ngOnChanges lifecycle hook call

Is it expected behavior that ngOnChanges lifecycle hook is not called in case of dynamic component loading? Only the constructor, ngOnInit and ngAfterViewInit are called for me. However according to the docs it should be called before ngOnInit.

I am loading the component like this:

@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

Upvotes: 8

Views: 6281

Answers (1)

SirWojtek
SirWojtek

Reputation: 348

According to discussion https://github.com/angular/angular/issues/8903 dynamic components loading should not trigger ngOnChanges in child component even after calling detectChanges because this event is reserved only for template bindings.

If your child component is loaded only in the dynamic way you can use Javascript setter instead of ngOnChanges. Here is the example:

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
  }
}

Upvotes: 14

Related Questions