我有一个angular2表单,它由一个父组件和几个子组件组成。我的服务中有一个ReplaySubject,当父进程需要保存内容,子进程订阅它并保存它的元素时,它就会发出。父组件需要知道所有子组件何时完成保存。(当保存完成时,我们仍将处于表单中。所以孩子们不能取消订阅。)我如何实现这一点?任何帮助都将不胜感激。谢谢
Parent component
----------------------
ngOnInit() {
// TODO: listen to child events and check if respose from all children received ??
}
save() {
console.log("Saving elements on parent component");
this.formService.save$.next(this.job.id);
}
Child 1
----------------
ngOnInit() {
this.formService.save$.subscribe(() =>
console.log("Save elements on child1 component");
// TODO: some event from here to say child 1 is done saving. ?
);
}
Child 2
----------------
ngOnInit() {
this.formService.save$.subscribe(() =>
console.log("Save elements on child2 component");
// TODO: some event from here to say child 2 is done saving. ?
);
}发布于 2017-07-24 15:32:23
假设父组件可以访问其模板中的子组件,则父组件可以在子组件完成保存时监听子组件发出的onSaved事件。
在ChildComponent中,您将定义一个输出事件:
@Output() onSaved = new EventEmitter<any>();
然后,在父模板中侦听该事件:
ParentComponent.html
<child-component (onSaved)="childSaved()"></child-component>
ParentComponent.ts
onSaved() { // Action when all child components have indicated save is completed }
这种类型的组件通信的Angular文档是here。
已经有一些很好的答案了,比如this one
https://stackoverflow.com/questions/45226365
复制相似问题