使用@ViewChildren的Angular 5访问div列表

时间:2018-10-26 21:38:27

标签: angular angular-renderer2

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

我的模板

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

2 个答案:

答案 0 :(得分:5)

this detailed answer中所述,ViewChildren的有效选择器包括组件类型,指令类型和模板引用变量。您无法使用CSS选择器(例如HTML元素类型(例如ViewChildren)或类名,使用div来检索DOM元素。

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

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

然后您可以使用模板引用变量,使用ViewChildren以代码的形式检索它们:

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

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

有关演示,请参见this stackblitz

答案 1 :(得分:1)

我能够通过创建自定义指令并像这样查询来获得所需的结果:

import { Directive, ElementRef, ViewChildren, Component, AfterViewInit, QueryList } from "@angular/core";

@Directive({selector: 'table th'})
export class DatatableHeadersDirective {
  nativeElement: HTMLTableHeaderCellElement = null;
  constructor(el: ElementRef) {
    this.nativeElement = el.nativeElement;
  }
}

@Component({
  selector: 'selctorname',
  templateUrl: 'htmlURL',
  styleUrls: ['styleURL'],
})
export class AwesomeDatatableComponent implements AfterViewInit {
  @ViewChildren(DatatableHeadersDirective) children: QueryList<DatatableHeadersDirective>;;

  ngAfterViewInit(){
    console.log(this.children.map(directive => directive.nativeElement))
  }
}