【问题标题】:Angular 5 access divs list using @ViewChildrenAngular 5 使用 @ViewChildren 访问 div 列表
【发布时间】:2018-10-26 21:38:26
【问题描述】:

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

【问题讨论】:

    标签: angular angular-renderer2


    【解决方案1】:

    this detailed answer 中所述,ViewChildren 的有效选择器包括组件类型、指令类型和模板引用变量。您无法使用 CSS 选择器(如 HTML 元素类型(例如 div)或类名)检索带有 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 以获取演示。

    【讨论】:

    • 我使用的是Angular 8,需要修改@ViewChildren语句如下:@ViewChildren("divs", { read: ElementRef }) divs: QueryList&lt;ElementRef&gt;;
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 2022-11-21
      • 2019-09-08
      • 2019-05-31
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      相关资源
      最近更新 更多