Issue
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?
Solution
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)
}
Answered By - Amit Chigadani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.