如何获取使用 ngfor 循环创建的 html 元素

jak*_*ard 5 ngfor angular

大家好,这里是我的问题的简化

我使用 *ngfor 在模板中创建了元素

<table >
  <thead>
  <tr>
    <th *ngFor="let item of array" > {{item}}</th>
  </tr>
  </thead>

 </table> 
Run Code Online (Sandbox Code Playgroud)

在 .ts 文件中我有表格

array = [1,2,3,4];
Run Code Online (Sandbox Code Playgroud)

然后当我尝试在控制台中显示元素时

  var cells = document.getElementsByTagName('th'); //or getElementById or anything..
  console.log(cells[1]);

Run Code Online (Sandbox Code Playgroud)

它显示 未定义

Man*_*gan 4

在 Angular 中,你可以采取不同的方法。

1)给出一些元素#theadEl的参考th,例如,

<th *ngFor="let item of array" #theadEl> {{item}}</th>
Run Code Online (Sandbox Code Playgroud)

2)然后在ts文件中进行一些导入@angular/core

import { Component, ViewChildren, ElementRef, QueryList,
  AfterViewInit } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

3)如果我们试图获取多个元素,例如,您需要将viewChildrenQueryList一起使用,

 @ViewChildren('theadEl') theadEl: QueryList<ElementRef>
Run Code Online (Sandbox Code Playgroud)

4)然后在ngAfterViewInit生命周期钩子中,您可以通过使用来实现结果,

  ngAfterViewInit(): void {
    const cells = this.theadEl.toArray();
    console.log(cells[1].nativeElement);
    console.log(cells[1].nativeElement.innerHTML);
  }
Run Code Online (Sandbox Code Playgroud)

最后,

组件.html

<table >
  <thead>
  <tr>
    <th *ngFor="let item of array" #theadEl> {{item}}</th>
  </tr>
  </thead>
 </table> 
Run Code Online (Sandbox Code Playgroud)

组件.ts

import { Component, ViewChildren, ElementRef, QueryList,
  AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';

  array = [1,2,3,4];

  @ViewChildren('theadEl') theadEl: QueryList<ElementRef>


  ngAfterViewInit(): void {
    const cells = this.theadEl.toArray();
    console.log(cells[1].nativeElement);
    console.log(cells[1].nativeElement.innerHTML);
  }

}
Run Code Online (Sandbox Code Playgroud)

在这里工作 Stackblitz...

注意:以上是最佳使用实践,但如果您想使用相同的方法document.getElementsByTagName('th');,那么您需要将代码放入ngAfterViewInit生命周期钩子,如下例所示。

使用 document.getElementsByTagName('th') 方法进行 Stackblitz

使用的原因ngAfterViewInit是,它完全初始化组件的视图。