Reputation: 892
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?
Upvotes: 13
Views: 15685
Reputation: 19
For angular13+, you'd better do as this
componentRef.instance.delEvent.subscribe(
value=>this.delOneItem(value)
)
this is for child @Output() delEvent: EventEmitter=new EventEmitter();
Upvotes: 2
Reputation: 29715
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)
}
Upvotes: 35