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

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

最佳答案

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/

相关文章:

angular - 如何在使用 Renderer2 创建的元素上设置指令和属性绑定(bind)

angular - 使用 HttpInterceptor 添加加载屏幕

typescript - 如何知道 ngOnChanges 中的哪些 @Input 变化?

css - 如何将鼠标悬停在 Angular 自动完成选项上

angular - 在 Angular 路由中从堆栈中删除以前的页面

angular - ngStyle VS 渲染器2?我应该使用什么?

css - Renderer2 通过 selectRootElement 选择元素使其内容消失

Angular 结构指令和 Renderer2

angular - 组件中获取的HTML元素坐标错误

angular - Ng-select 样式问题