Search code examples
angularangular-cdk

Building cdk modal - ngOnInit is not triggered and no data is passed


I'm trying to build modals library that is dependent only on CDK. Modal is opened with service and I pass entryComponent to render it in modal.

Here is sample: https://stackblitz.com/edit/angular-ofzpks?file=src%2Fapp%2Fmodal.component.ts

In modal itself I'm creating component with factory:

const compRef = this.componentFactoryResolver.resolveComponentFactory<any>(this.modalContentComponent);
const componentRef = this.modalContainer.createComponent(compRef);

I have two problems:

  1. I have to trigger componentRef.instance.ngOnInit(); manually
  2. I pass some data to that component: componentRef.instance.name = this.data.name; but component never renders it

Solution

  • In your modal.component.ts, use ngOnInit instead of ngAfterViewInit:

    ngOnInit() {
      const compRef = this.componentFactoryResolver.resolveComponentFactory<any>(this.modalContentComponent);
      const componentRef = this.modalContainer.createComponent(compRef);
      componentRef.instance.name = this.data.name;
    }
    

    Updated StackBlitz


    Doing it this way means that ngDoCheck will run and detect the changes for you since ngDoCheck runs directly after ngOnInit.