【问题标题】:Iterate through multiple @ViewChild instances of the same component angular2遍历同一组件angular2的多个@ViewChild实例
【发布时间】:2017-09-05 05:48:02
【问题描述】:

我有一个 Ionic 2 应用程序,其 ParentComponent 调用 ChildComponent @ViewChild 方法来启动多个 ChildComponents。其中一个 ChildComponents 在视图中使用不同的参数实例化了两次,如下所示:

<ChildComponent [startFrom]="0" [limitTo]="1"></ChildComponent>
<ChildComponent [startFrom]="1" [limitTo]="1"></ChildComponent>

在离线/在线设备状态更改后,我调用 ChildComponent 的方法来更新它返回的项目列表。

@ViewChild(ChildComponent) childComponent: ChildComponent;

ngOnInit(): void {
    this.networkService.connectSubscription(() => {
        this.childComponent.getItems();
    });
}

这里的问题是this.childComponent 只获得了两者的第一个 ChildComponent 实例。

有没有办法遍历同一个@ViewChild 组件的多个实例,以便我可以执行this.childComponent1.getItems()this.childComponent2.getItems() 之类的操作?

感谢您的帮助。

【问题讨论】:

    标签: javascript angular ionic2 angular2-components


    【解决方案1】:
    @ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;
    
    ngAfterViewInit(): void {
        this.networkService.connectSubscription(() => {
            this.childComponents.toArray();
        });
    }
    

    【讨论】:

    • 当然。烦人的部分是我自己this.childComponents 到了这条线,但不知道toArray()。感谢您的帮助。
    • 我知道,这不容易被发现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2017-12-07
    • 2017-04-06
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多