使用@viewchild访问多个viewchildren [英] Access multiple viewchildren using @viewchild

查看:157
本文介绍了使用@viewchild访问多个viewchildren的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a custom component which i have placed in a for loop e.g

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

     <customcomponent></customcomponent>

</div>

其输出将是:

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

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

I would like to know how i can get a reference to these components using @viewchild syntax or any other means when the number of these components can vary

可以给组件起一个名称,例如

when the component can be given a name e.g

<customcomponent #compID></customcomponent>

然后我可以如下引用它:

I can then reference it as follows:

@ViewChild('compID') test: CustomComponent

在不是这种情况(例如可能使用索引)的情况下如何引用呢?

How do i reference it when this is not the case e.g using an index possibly?

(此问题与先前已问过的其他问题均与使用ElementRef无关,如下面列出的答案所示).此问题与访问多个@ViewChild和使用列表查询有关.

(This question does not relate to using ElementRef as per other questions that have been previously asked as can be seen by the answers listed below) This question relates to the accessing multiple @ViewChild and using list queries.

推荐答案

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

Use @ViewChildren from @angular/core to get a reference to the components

模板

<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̶

这篇关于使用@viewchild访问多个viewchildren的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆