@Component({
(...)
})
export class ChildComponent {
@Input()
parentSubject:Subject<any>;
ngOnInit() {
this.parentSubject.subscribe(event => {
// called when the notifyChildren method is
// called in the parent component
});
}
ngOnDestroy() {
// needed if child gets re-created (eg on some model changes)
// note that subsequent subscriptions on the same subject will fail
// so the parent has to re-create parentSubject on changes
this.parentSubject.unsubscribe();
}
}
否则,您可以以类似的方式利用包含此类主题的共享服务...
5
为了后代,我想我会提到 the more conventional solution to this :只需获取对ViewChild的引用,然后直接调用其中一个方法 .
3 回答
我认为这份文档可能对您有所帮助:
实际上,您可以利用父级为其子级提供的可观察/主题 . 像这样的东西:
子组件可以简单地订阅此主题:
否则,您可以以类似的方式利用包含此类主题的共享服务...
为了后代,我想我会提到 the more conventional solution to this :只需获取对ViewChild的引用,然后直接调用其中一个方法 .
如果我正确地理解了这个问题,那么这里可能会采用更简单的方法 . 假设 -
OP在父组件中有一个保存按钮
需要保存的数据位于子组件中
可以从服务访问子组件可能需要的所有其他数据
在父组件中
在孩子..
这只是将按钮单击发送到子组件 . 子组件可以从那里独立保存数据 .
编辑:如果父模板中的数据也需要与按钮单击一起传递,这也可以通过这种方法实现 . 如果是这种情况,请告诉我,我将更新代码示例 .