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

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

问题描述

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

<customcomponent></customcomponent>

输出结果为:

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

我想知道当这些组件的数量可能会有所不同时,如何使用@viewchild 语法或任何其他方式获得对这些组件的引用

当组件可以命名时,例如

然后我可以按如下方式引用它:

@ViewChild('compID') 测试:CustomComponent

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

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

解决方案

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

模板

<customcomponent #cmp></customcomponent>

组件

import { ViewChildren, QueryList } from '@angular/core';/** 处理模板中的 cmp 标签 */@ViewChildren('cmp') 组件:QueryList;ngAfterViewInit(){//打印 CustomComponent 对象的数组console.log(this.components.toArray());}

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

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>

The output of which will be:

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

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?

(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.

解决方案

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

template

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

component

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 访问多个视子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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