I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following:
PARENT COMPONENT
Within the .ts file:
@ViewChild(InjectDirective) injectComp: InjectDirective;
constructor (private componentFactoryResolver: ComponentFactoryResolver) {}
addComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
viewContainerRef.createComponent(componentFactory);
}
And in the .html file:
<button (click)="addComponent()">Add Component</button>
Additionally, there is a custom directive implemented:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appInject]'
})
export class InjectDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
Lastly, we have the child component:
CHILD COMPONENT:
Inside the child component, the following code exists:
export class ChildComponent implements OnInit {
@ViewChild('viewer') private viewer: ElementRef;
}
In the HTML template of the child component:
<div>I AM A COMPONENT</div>
The goal is to pass unique data to each newly created child component.
How can I achieve this?