Search code examples
angularangular12

Angular 12 trying to pass data to a dynamic loaded component, but uncertain on how to achieve it


I have a component that I'm loading dynamically.

Here is the code:

app.component.ts

    @ViewChild(InjectDirective, { static: true }) injectComp!: InjectDirective;
    
      componentFactory: any;
      constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    
      add(): void {
        this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(ModalComponent);
        const viewContainerRef = this.injectComp.viewContainerRef;
        viewContainerRef.createComponent(this.componentFactory);
      }

app.component.html

    <button (click)="add()">Dynamically Add Component</button>  
    <ng-template appInject></ng-template>

and the directive:

    import { Directive, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[appInject]'
    })
    export class InjectDirective {
    
      constructor(public viewContainerRef: ViewContainerRef) {}
    
    }

I need to pass some data to the component that's dynamically loaded.

How do I do that?


Solution

  • The createComponent function is returning the component's instance. You can solve this problem by passing this example as a parameter to the directive.

    app.component.ts

    add(): void {
      this.componentFactory =
        this.componentFactoryResolver.resolveComponentFactory(ModalComponent);
      const viewContainerRef = this.injectComp.viewContainerRef;
      const component = viewContainerRef.createComponent<ModalComponent>(
        this.componentFactory
      );
      // pass component to directive
      this.injectComp.modalComponent = component.instance;
    }
    

    inject.directive.ts

    @Input() set modalComponent(component: ModalComponent) {
       // You can pass parameter here
       component.zIndex = Math.random() * 10;
    }
    

    Example Project here: https://stackblitz.com/edit/angular-ivy-ooghrz?file=src%2Fapp%2Finject.directive.ts