angular – 使用@viewchild访问多个viewchildren

参见英文答案 > How can I select an element in a component template?10个
我已经创建了一个自定义组件,我将其置于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 / 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._results);
}

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...