我想获取所有以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
}发布于 2018-10-27 05:54:55
正如在this detailed answer中提到的,ViewChildren的有效选择器包括组件类型、指令类型和模板引用变量。你不能使用像ViewChildren元素类型(例如div)或类名这样的CSS选择器来检索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。
发布于 2021-01-17 00:56:57
通过创建自定义指令并像这样查询它,我能够获得所需的结果:
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))
}
}https://stackoverflow.com/questions/53016596
复制相似问题