我想获取所有以 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
}
最佳答案
如 this detailed answer 中所述,ViewChildren
的有效选择器包括组件类型、指令类型和模板引用变量。您不能使用 HTML 元素类型(例如 div
)或类名等 CSS 选择器通过 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用于演示。
关于使用@ViewChildren 的 Angular 5 访问 div 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53016596/