[英]Angular 2 ng-content receive event from child component
我正在構建一個包含多個動態面板的頁面,每個子面板都具有相同的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和ref的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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.