contentChildrenとその親の間で通信するための好ましい方法は何ですか?角2: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に情報を送り返すことができますか?
UPDATE:私は何が起こっていなかった子供のメソッドを呼び出すためにしようとしていたときと述べた以下のコメントで
。まあそれは、私が親のシナリオにあなたの子供のために
ngAfterContentInit()
{
this.childrenList.changes
.subscribe(list => {
list.forEach(c => c.doSomething())
}
);
}
あなたはchildrenListにループを呼び出すことができる子に関数を作成することができます。同様に、親でサブスクライブするイベントエミッタを作成することもできます。 –