当子组件发出事件时,我希望函数在父组件中触发。子组件通过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);
}
答案 0 :(得分:2)
感谢Krim,通过该链接解决了
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);
}