使用@ViewChild访问多个ViewChild。

202

我创建了一个自定义组件,将其放置在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并使用列表查询。

2个回答

339

使用来自 @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());
}

实时演示


3
它说 ._results 是一个私有函数。另外,components 对我来说只是一个单独的组件,而不是列表。你还需要什么帮助吗? - Sam Alexander
21
你可以使用 this.components.toArray() 来获取具有 #cmp 名称的组件数组。 - DavidGSola
3
Ajax响应是如何工作的?@ViewChildren在初始化视图后被触发,但在模型更改(对于ngFor)后不会被触发。我该如何触发它? - elporfirio
1
{btsdaf} - BeetleJuice
@DavidGSola 当我尝试使用this.components.toArray()时,返回的是[]。而且._results不是我可以添加toArray()函数的方法。那么我该如何获取这些子元素呢? - rmcsharry
1
没关系,我找到了这篇更详细的解释:https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e 在@ViewChildren中使用组件名称会返回不同的结果,与在HTML中分配的#name不同。 - rmcsharry

83

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接