contentChildren与其“父”之间的首选通信方式是什么?Angular 2:contentChildren communication
更新:孩子可能不是直接父...
鉴于儿童的随机列表,由一组包装:
<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?
UPDATE:
在下面我提到的,当我尝试调用对孩子没有什么方法正在发生的意见。那么事实证明,我需要订阅的变化,等待孩子......然后我就能够调用
ngAfterContentInit()
{
this.childrenList.changes
.subscribe(list => {
list.forEach(c => c.doSomething())
}
);
}
你可以在child上创建一个函数,你可以调用childrenList循环,类似的,你可以创建一个你可以在父类中订阅的eventemitter。 –