来自Angular 6中动态创建的组件的@Output

时间:2019-01-15 05:53:39

标签: angular angular6

在我的angular 6项目中,我有一个动态创建的组件,如下所示:

@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是父级,TasksComponent是子级。现在,我希望使用TasksComponent将一些数据从StaffDashComponent传递到@Output。我该如何实现?

2 个答案:

答案 0 :(得分:3)

对于动态创建的子组件,您必须订阅父组件中的输出事件。

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));
}

儿童组合

@Output() outputEvent : EventEmitter<boolean> = new EventEmitter<boolean>(); 
someFunc() {
      this.outputEvent.emit(true)
}

答案 1 :(得分:0)

创建动态组件

步骤1:创建组件

ng g c child

步骤2:在声明数组和条目组件的App.module.ts文件中添加childComponent

 @NgModule({
  declarations: [childComponent],
  imports: [],
  entryComponents: [childComponent]
  bootstrap: [AppComponent]
})

步骤3 父组件的HTML代码

<template #modalcontainer></template>

步骤4 父组件TS代码

import { Component, OnInit,ViewContainerRef, ComponentFactoryResolver} from 
'@angular/core';
import {childComponent} from './child.Component';
.
.
.

@ViewChild('modalcontainer', { read: ViewContainerRef }) entry: ViewContainerRef;
. 
.
.
createComponent(childComponent, moduleData) {
   this.entry.clear();
   const factory = this.resolver.resolveComponentFactory(childComponent);
   this.componentRef = this.entry.createComponent(factory);
   // if want to pass data to child component
   var data = {};
   data["id"] = moduleData.id;
   this.componentRef.instance.moduleData = data;
 }

在这里您可以从父组件获取数据

export childComponent {
   // In moduleData you will get data passed from parent component
   @Input() moduleData:any;
}

希望这会有所帮助