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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With