Angular 5 使用@ViewChildren 访问 div 列表

Angular 5 access divs list using @ViewChildren

我想获取所有以 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  
}

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

使其适用于您的情况的一种方法是使用 ngFor 循环生成 div 元素,并将模板引用变量 #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

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

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