contentChildren与其“父”之间通信的首选方法是什么?
更新的:子可能不是直接父母.
给出一个由一组儿童组成的随机列表:
<child-group>
<div>Some other content, child may not be direct parent...</div>
<child *ngFor="let item of data$ | async;"></child>
</child-group>儿童部分:
@Component({
selector: 'child',
template: '<button (click)="didSomethingTellGroup()"></button>',
styleUrls: ['child.component.scss'],
})
export class ChildComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
doSomething() {
console.log('Called from group component')
}
didSomethingTellGroup() {
//EventEmitter?
//Observable?
}
}父组件:
@Component({
selector: 'child-group',
template: '<ng-content></ng-content>',
styleUrls: ['child-group.component.scss'],
})
export class ChildGroupComponent implements AfterContentInit {
@ContentChildren(ChildComponent) childrenList: QueryList<ChildComponent>;
constructor() {
}
ngAfterContentInit() {
//How to invoke doSomething() on all children?
childrenList...
//How can I get notification from one or all children, that it did something, or its state has changed.
childrenList...
}
}如何从ChildGroup调用子方法?孩子如何将信息发送回ChildGroup呢?
更新:
在下面的评论中,我提到,当我试图在子节点上调用一个方法时,什么都没有发生。事实上,我需要订阅更改并等待我能够调用的children...then。
ngAfterContentInit()
{
this.childrenList.changes
.subscribe(list => {
list.forEach(c => c.doSomething())
}
);
}发布于 2017-03-09 19:16:58
前面的答案是完全正确的,使用@Output并循环遍历您的QueryList是可行的,但是如果正如您提到的,您的孩子不是直接的孩子,您可以使用服务作为通信香奈儿。
下面是一个非常基本的柱塞,演示了这一点:http://plnkr.co/edit/VuYiz7gVB42PEnnk2d8C (我不是可观察的专家,所以也许可以改进这一点)。
基本上,当您单击子组件的一个按钮时,它使用:
this.myService.sendToParent(this.random);若要通过服务向父级发送消息,请执行以下操作。在这个函数中,服务通过一个可观察到的消息发送给父程序:
this.parentSubject.next(value);以前,父级订阅了此可观察到的内容:
this.service.getParentMessages().subscribe((data) =>
{
alert('Something changed from a children: ' + data);
this.service.sendToChildren(data);
});如您所见,当它接收到一个新值时,它使用函数sendToChildren通过服务向他的所有子节点发送一条消息(同样的原则也适用于此)。当子节点接收到消息时,它会更改最终显示在组件中的值。
发布于 2017-03-09 19:02:14
对于您的子到父场景,@Output事件发射器是您的最佳选择。您的子组件正在将内部操作本身(用户单击某个位置)转换为与业务相关的事件,该组件的任何用户都可以侦听该事件。
至于父母打电话给孩子的问题,你已经是你的榜样了。只需在QueryList上迭代,并在您的子组件上调用任何您希望的方法。
ngAfterContentInit() {
//How to invoke doSomething() on all children?
this.childrenList.forEach ( c => c.doSomething(); )
...
}https://stackoverflow.com/questions/42703270
复制相似问题