Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Output from dynamically created Component in Angular 6

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?

like image 206
toothful Avatar asked Jan 15 '19 05:01

toothful


People also ask

Can we create component dynamically in Angular?

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.

How can you dynamically load the component?

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.

What can I use instead of ComponentFactoryResolver?

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.


1 Answers

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)
}
like image 116
Amit Chigadani Avatar answered Oct 14 '22 01:10

Amit Chigadani