Angular 2 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>

我可以创建一个共享服务,但是将布尔值从子项传递到父项似乎有些矫枉过正。

有什么想法吗?

谢谢

有几种方法

<panel #p>
    <child-panel-one (emittedEvent)="p.func($event)"></child-panel-one>
</panel>

但这需要<panel>的用户设置事件绑定

或者你可以像 Angular2 中所示的 DOM 事件如何知道任何表单输入字段何时失去焦点

或者您可以使用"@ContentChildren(("然后强制订阅

@ContentChildren(ChildPanelOne) childPanels:QueryList<ChildPanelOne>
ngAfterContentInit() {
  this.childPanels.toArray().forEach(cp => cp.emittedValue.subscribe(() => ...));
}

但这要求所有子面板都是预定义的类型。

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

从内容子级捕获事件的另一种方法是获取父 comp 的引用并定义

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
}

工作演示 ( 也检查这个 (

最新更新