【问题标题】:Access multiple viewchildren using @viewchild使用@viewchild 访问多个viewchild
【发布时间】:2017-03-03 02:16:47
【问题描述】:

我创建了一个自定义组件,我将它放在一个 for 循环中,例如

<div *ngFor="let view of views">

     <customcomponent></customcomponent>

</div>

其输出将是:

<customcomponent></customcomponent>
<customcomponent></customcomponent>
<customcomponent></customcomponent>

我想知道当这些组件的数量可以变化时,如何使用@viewchild 语法或任何其他方式获得对这些组件的引用

当组件可以被命名时,例如

<customcomponent #compID></customcomponent>

然后我可以如下引用它:

@ViewChild('compID') test: CustomComponent

如果不是这种情况,例如可能使用索引,我如何引用它?

(这个问题与使用 ElementRef 无关,正如之前提出的其他问题一样,可以从下面列出的答案中看出)这​​个问题与访问多个 @ViewChild 和使用列表查询有关。

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用@angular/core 中的@ViewChildren 获取对组件的引用

    模板

    <div *ngFor="let v of views">
        <customcomponent #cmp></customcomponent>
    </div>
    

    组件

    import { ViewChildren, QueryList } from '@angular/core';
    
    /** Get handle on cmp tags in the template */
    @ViewChildren('cmp') components:QueryList<CustomComponent>;
    
    ngAfterViewInit(){
        // print array of CustomComponent objects
        console.log(this.components.toArray());
    }
    

    l̶i̶v̶e̶ ̶d̶e̶m̶o̶

    【讨论】:

    • 它说 ._results 是一个私有函数。还有这个。 components 只是一个单一的组件,对我来说不是一个列表。您还能提供更多帮助吗?
    • @SamAlexander 您可以使用 this.components.toArray() 获取具有#cmp 名称的组件数组
    • 它如何在 Ajax 响应中工作?,@ViewChildren 在初始化视图后触发,但在模型(用于 ngFor)更改后不会触发。我该如何触发呢?
    • @elporfirio 实现AfterViewChecked 并编写方法ngAfterViewChecked。在视图更新后的每个更改周期都会触发此方法。在其中,您可以测试是否已定义 viewChild 实例。 See the docs
    • 没关系,我发现这可以更详细地解释事情:netbasal.com/… 在@ViewChildren 中使用组件的名称与使用您在 HTML 中指定的#name 给出的返回结果不同。跨度>
    【解决方案2】:

    将@ViewChildren 装饰器与QueryList 结合使用。这两个都来自“@angular/core”

    @ViewChildren(CustomComponent) customComponentChildren: QueryList&lt;CustomComponent&gt;;

    与每个孩子一起做的事情看起来像: this.customComponentChildren.forEach((child) =&gt; { child.stuff = 'y' })

    在 angular.io 上还有进一步的文档,特别是: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 2016-08-07
      • 2018-12-09
      • 1970-01-01
      • 2017-08-28
      • 2018-03-01
      • 2020-03-07
      • 1970-01-01
      • 2019-10-18
      相关资源
      最近更新 更多