Angular 2 : contentChildren communication

标签 angular angular2-template

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/

相关文章:

Angular 放大初始化 Cognito : Profile configuration is missing for default

node.js - Azure Blob Node.js 下载 blob 文件

javascript - Angular2 在等待数据加载时更新 View

javascript - ng2 初始化 DOM 属性一次并删除更改检测

Angular 2 动态页面页眉和页脚

angular - 使用 Angular 浏览静态 Html 文件

Angular DevExtreme 主题

angular - 为什么没有 <app-root> 的其他组件不会出现在 index.html 上?

angular - 由于 ngIf,保持隐藏组件的引用

javascript - Angular 2中的密码验证,满足以下条件: