angular - 如何获取使用 ngfor 循环创建的 html 元素
问题描述
大家好这里是我的问题的简化
我使用 *ngfor 在模板中创建了元素
<table >
<thead>
<tr>
<th *ngFor="let item of array" > {{item}}</th>
</tr>
</thead>
</table>
在 .ts 文件中我有表格
array = [1,2,3,4];
然后当我尝试在控制台中显示元素时
var cells = document.getElementsByTagName('th'); //or getElementById or anything..
console.log(cells[1]);
它显示 未定义
解决方案
在 Angular 中,您可以采取不同的方法。
1)给一些元素参考,比如#theadEl
,th
<th *ngFor="let item of array" #theadEl> {{item}}</th>
2)然后在ts
文件中进行一些@angular/core
类似的导入,
import { Component, ViewChildren, ElementRef, QueryList,
AfterViewInit } from '@angular/core';
3)如果我们试图获取多个元素,您需要将viewChildren与QueryList一起使用,例如,
@ViewChildren('theadEl') theadEl: QueryList<ElementRef>
4)然后在ngAfterViewInit生命周期钩子中,你可以通过使用来达到结果,
ngAfterViewInit(): void {
const cells = this.theadEl.toArray();
console.log(cells[1].nativeElement);
console.log(cells[1].nativeElement.innerHTML);
}
最后,
组件.html
<table >
<thead>
<tr>
<th *ngFor="let item of array" #theadEl> {{item}}</th>
</tr>
</thead>
</table>
组件.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);
}
}
注意:以上是使用的最佳实践,但如果你想使用相同的方法document.getElementsByTagName('th');
,那么你需要将代码制作成ngAfterViewInit
生命周期钩子,如下例所示。
Stackblitz 与 document.getElementsByTagName('th') 方法
使用的原因ngAfterViewInit
是,它完全初始化了一个组件的视图。