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?
CodePudding user response:
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/app/inject.directive.ts