使用@ViewChildren的Angular 5访问div列表 [英] Angular 5 access divs list using @ViewChildren

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

问题描述

我想获取所有以id'div'开头的div.为此,我使用@ViewChildren但由于我有一个空数组而无法访问div,为什么?

I want to fetch all divs starting with the id 'div'. To do so, i use @ViewChildren but i'm not able to access the divs because i have an empty array , why ?

我的模板

<div id="div-1">Div 1</div>
<div id="div-2">Div 2</div>
<input type="button" (click)="getDivs()">

组件

@ViewChildren('div') divs: QueryList<any>;
divList : any[];

getDivs(){ 
   this.divList = this.divs.filter(x => x.id.lastIndexOf('div-', 0) === 0);  
   console.log(this.divList);  
      // this.divList return an empty array but i should have two results  
}

推荐答案

此详细答案中所述,有效ViewChildren的选择器包括组件类型,指令类型和模板引用变量.您不能使用CSS选择器(例如HTML元素类型(例如div)或类名)使用ViewChildren检索DOM元素.

As mentioned in this detailed answer, the valid selectors for ViewChildren include component types, directive types, and template reference variables. You cannot retrieve DOM elements with ViewChildren using CSS selectors like HTML element types (e.g. div) or class names.

一种适合您的情况的方法是使用ngFor循环生成div元素,并将模板引用变量#divs与其关联:

One way to make it work in your case is to generate the div elements with an ngFor loop, and associate a template reference variable #divs to them:

<div #divs *ngFor="let item of [1,2]" [id]="'div-' + item">Div {{item}}</div>
<button (click)="getDivs()">Get divs</button>

然后您可以使用模板引用变量使用ViewChildren在代码中检索它们:

You can then retrieve them in code with ViewChildren, using the template reference variable:

@ViewChildren("divs") divs: QueryList<ElementRef>;

getDivs() {
  this.divs.forEach((div: ElementRef) => console.log(div.nativeElement));
}

有关演示,请参见此stackblitz .

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

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