gpt4 book ai didi

Angular 2 : contentChildren communication

转载 作者:行者123 更新时间:2023-12-01 21:57:11 25 4
gpt4 key购买 nike

contentChildren 与其“父级”之间通信的首选方法是什么?

更新: child 可能不是直接 parent ...

给定一个随机的子列表,由一组包裹:

<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?

更新:

在下面的评论中,我提到当我尝试调用 children 的方法时,什么也没有发生。事实证明,我需要订阅更改并等待 children ......然后我就可以调用

ngAfterContentInit()
{
this.childrenList.changes
.subscribe(list => {
list.forEach(c => c.doSomething())
}
);
}

最佳答案

对于您的 child 到 parent 的场景,@Output 事件发射器是您最好的选择。您的子组件正在将其本身的内部操作(用户单击某处)转换为该组件的任何用户都可以监听的业务相关事件。

至于 parent 调用 child ,你的例子已经差不多了。只需迭代 QueryList 并在子组件上调用您希望的任何方法即可。

ngAfterContentInit() {    
//How to invoke doSomething() on all children?
this.childrenList.forEach ( c => c.doSomething(); )
...
}

关于 Angular 2 : contentChildren communication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42703270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com