简体   繁体   English

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

[英]Angular 5 access divs list using @ViewChildren

I want to fetch all divs starting with the id 'div'.我想获取所有以 id 'div' 开头的 div。 To do so, i use @ViewChildren but i'm not able to access the divs because i have an empty array , why ?为此,我使用 @ViewChildren 但我无法访问 div,因为我有一个空数组,为什么?

My template我的模板

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

Component成分

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

As mentioned in this detailed answer , the valid selectors for ViewChildren include component types, directive types, and template reference variables.如此详细答案中所述, ViewChildren的有效选择器包括组件类型、指令类型和模板引用变量。 You cannot retrieve DOM elements with ViewChildren using CSS selectors like HTML element types (eg div ) or class names.您不能使用诸如 HTML 元素类型(例如div )或类名之类的 CSS 选择器通过ViewChildren检索 DOM 元素。

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:使其在您的情况下工作的一种方法是使用ngFor循环生成div元素,并将模板引用变量#divs到它们:

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

You can then retrieve them in code with ViewChildren , using the template reference variable:然后,您可以使用模板引用变量通过ViewChildren在代码中检索它们:

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

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

See this stackblitz for a demo.有关演示,请参阅 此 stackblitz

I was able to achieve needed result by creating custom directive and querying it like this:我能够通过创建自定义指令并像这样查询它来获得所需的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM