【发布时间】:2017-07-30 21:44:45
【问题描述】:
在 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 调用子方法? Child 如何将信息发送回 ChildGroup?
更新:
在下面的 cmets 中,我提到当我试图对孩子调用一个方法时,什么也没发生。好吧,事实证明我需要订阅更改并等待孩子们......然后我就可以调用
ngAfterContentInit()
{
this.childrenList.changes
.subscribe(list => {
list.forEach(c => c.doSomething())
}
);
}
【问题讨论】:
-
你可以在child上创建一个函数,你可以在childrenList上调用循环,同样你可以创建一个eventemitter,你可以在parent中订阅。