Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Dynamic Component loading ngOnChanges lifecycle hook call

Tags:

angular

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

like image 920
fjozsef Avatar asked Nov 15 '16 13:11

fjozsef


1 Answers

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
  }
}
like image 141
18 revs, 8 users 77% Avatar answered Nov 07 '22 20:11

18 revs, 8 users 77%