在 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);
}
最后,
component.html
<table >
<thead>
<tr>
<th *ngFor="let item of array" #theadEl> {{item}}</th>
</tr>
</thead>
</table>
component.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);
}
}
Working Stackblitz Here...
注意:以上是最佳使用实践,但如果你想使用与document.getElementsByTagName('th');相同的方法,那么你需要将代码放入ngAfterViewInit生命周期钩子为像下面的例子。
Stackblitz with document.getElementsByTagName('th') method
使用ngAfterViewInit的原因是,它完全初始化了一个组件的视图。