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。 –