Angular 2 ng内容从子组件接收事件

Angular 2 ng内容从子组件接收事件,angular,angular2-ngcontent,Angular,Angular2 Ngcontent,我正在构建一个包含多个动态面板的页面,每个子面板都有相同的HTML,因此我创建了一个父面板组件来包装每个子面板 问题是我想把一个事件从孩子发送到小组,但我似乎找不到答案。以下是我目前掌握的情况: // Panel Panel Component @Component({ selector: 'panel', template: ` <div (emittedEvent)="func($event)"> <ng-content><

我正在构建一个包含多个动态面板的页面,每个子面板都有相同的HTML,因此我创建了一个父面板组件来包装每个子面板

问题是我想把一个事件从孩子发送到小组,但我似乎找不到答案。以下是我目前掌握的情况:

// Panel Panel Component
@Component({
    selector: 'panel',
    template: `
    <div (emittedEvent)="func($event)">
        <ng-content></ng-content>
    </div>
    `
})
export class PanelComponent {

    constructor() {}

    func(event) {
    // Do stuff with the event
    }
}
// Child Panel Component (one of many)
@Component({
selector: 'child-panel-one',
template: `
    // Template stuff
    <button (click)="emitEvent()">Click</button>
`
})
export class ChildPanelOne {
emittedValue: Boolean = false;

@Output() emittedEvent = new EventEmitter();

constructor() {}

private emitEvent() {
    this.emittedValue = true;

    this.emittedEvent.emit(this.emittedValue)
}
}
//
// Main Parent Template
<panel>
    <child-panel-one></child-panel-one>
</panel>
//面板组件
@组成部分({
选择器:“面板”,
模板:`
`
})
导出类组件{
构造函数(){}
职能(活动){
//与活动有关的事情
}
}
//子面板组件(多个组件之一)
@组成部分({
选择器:'子面板一',
模板:`
//模板材料
点击
`
})
导出类ChildPanelOne{
emittedValue:Boolean=false;
@Output()emittedEvent=新的EventEmitter();
构造函数(){}
私有事件(){
this.emittedValue=true;
this.emittedEvent.emit(this.emittedValue)
}
}
//
//主父模板
我可以创建一个共享服务,但将布尔值从子级传递到父级似乎有些过分

有什么想法吗

谢谢

有几种方法

<panel #p>
    <child-panel-one (emittedEvent)="p.func($event)"></child-panel-one>
</panel>
但这要求所有子面板都是预定义类型


您还可以将共享服务与子组件注入并用于向父组件发送事件的可观察服务一起使用。

从内容子组件捕获事件的另一种方法是获取父组件的ref并定义

constructor(app:AppComponent){ //<-- get the ref of the parent component
    app['clic'] = this.clic; //<-- declare function and bind our function 
    this.name = 'myself';
}

clic(){
    alert('clicked');
}

ngOnDestroy() {
    delete this.app['clic']; // <-- get rid of the function from parent component, when we are done
}

构造函数(应用程序:AppComponent){//谢谢你的回答和链接。该服务似乎是最好的方式-这样面板组件就不需要像你上面描述的那样定义所有的子面板。我已经创建了一个非常简单的服务,适用于面板及其子面板,对于其他有类似问题的人,这个Plunkr演示了共享发射器服务,谢谢谢谢你的反馈。很高兴听到你能找到一个适合你的解决方案。我也会使用一个服务。你也可以让所有的内容子项从一个具有通用输出(例如onChange)的基础组件继承,并在你的组件中使用其模板中的订阅。
ngAfterContentInit() {
  this.childPanels.toArray().forEach(cp => cp.emittedValue.subscribe(() => ...));
}
constructor(app:AppComponent){ //<-- get the ref of the parent component
    app['clic'] = this.clic; //<-- declare function and bind our function 
    this.name = 'myself';
}

clic(){
    alert('clicked');
}

ngOnDestroy() {
    delete this.app['clic']; // <-- get rid of the function from parent component, when we are done
}