[英]Access parent component from child component when parent component using ng-content Angular
[英]Angular parent component listen to a ng-content child component
我希望當子組件發出事件時函數在父組件內觸發。 子組件通過ng-content傳遞給父組件。 我簡化了我要執行的操作的代碼,但似乎無法讓孩子向父母投降。 我想通過ng-content傳遞孩子,因為子組件可以是多種組件,而不是一個特定的組件
例:
main.ts
<parent-component>
<child-component></child-component>
</parent-component>
parent.component.ts
<div>
{{ this.value }}
<ng-content (updated)="updateParentValue()"></ng-content> <-- this doesn't work
</div>
updateParentValue(value) {
this.value = value;
}
child.component.ts
<div>
<span (click)="updateStuff()">update</span>
</div>
@Output() updated = new EventEmitter();
updateStuff() {
// Stuff
this.updated.emit(this.value);
}
謝謝克里姆,用那個鏈接解決了
main.ts
<parent-component>
<child-component></child-component>
</parent-component>
parent.component.ts
<div>
{{ this.value }}
<ng-content></ng-content>
</div>
@ContentChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
ngAfterViewInit() {
this.childComponents.forEach((childComponent: ChildComponent) => {
childComponent.updated.subscribe((item) => this.updateParentValue(item));
});
}
updateParentValue(value) {
this.value = value;
}
child.component.ts
<div>
<span (click)="updateStuff()">update</span>
</div>
@Output() updated = new EventEmitter();
updateStuff() {
// Stuff
this.updated.emit(this.value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.