In my angular 6 project, I have a dynamically created component like below:
@Component({
selector: 'app-staff-dash',
template: `
<template #tasksContainer></template>
`
})
export class StaffDashComponent implements OnInit {
componentRef: any;
factory: any;
@ViewChild('tasksContainer', { read: ViewContainerRef }) tasksEntry: ViewContainerRef;
constructor(
@Inject(ComponentFactoryResolver) private resolver: ComponentFactoryResolver
) {
}
ngOnInit() {
this.createTasksComponent();
}
createTasksComponent(): void {
this.tasksEntry.clear();
this.factory = this.resolver.resolveComponentFactory(TasksComponent);
this.componentRef = this.tasksEntry.createComponent(this.factory);
}
}
StaffDashComponent
is the parent and TasksComponent
is the child. Now I want some data to be passed from TasksComponent
to StaffDashComponent
using @Output
. How can I achieve that?
If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.
To dynamically load the component, we use the directive as an anchor and create the component into its position in the DOM. The createComponent method requires the component type, not the instance.
In Angular 13 the new API removes the need for ComponentFactoryResolver being injected into the constructor, like you did in your code. Now to dynamically create a component you have to use ViewContainerRef.
For dynamically created child component, You have to subscribe to output event within the parent component.
parent.comp
createTasksComponent(): void {
this.tasksEntry.clear();
this.factory = this.resolver.resolveComponentFactory(TasksComponent);
this.componentRef = this.tasksEntry.createComponent(this.factory);
//subscribe to child output event
this.componentRef.instance.outputEvent.subscribe(val => console.log(val));
}
child comp
@Output() outputEvent : EventEmitter<boolean> = new EventEmitter<boolean>();
someFunc() {
this.outputEvent.emit(true)
}
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