要遍历通过
生成的 HTML 元素,你可以使用 Angular 的 @ViewChild
装饰器来获取 ng-template
的引用,然后使用 TemplateRef
类型来访问其内容。
下面是一个示例代码:
HTML 文件:
{{ item }}
Component 文件:
import { Component, AfterViewInit, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('templateRef', { read: TemplateRef }) templateRef: TemplateRef;
items = ['Item 1', 'Item 2', 'Item 3'];
constructor(private viewContainerRef: ViewContainerRef) { }
ngAfterViewInit(): void {
this.viewContainerRef.createEmbeddedView(this.templateRef);
const elements = this.viewContainerRef.element.nativeElement.querySelectorAll('div');
elements.forEach(element => {
console.log(element.innerText);
});
}
}
在上面的示例中,我们使用 @ViewChild
装饰器获取 ng-template
的引用,并将其声明为 TemplateRef
类型。在 ngAfterViewInit
生命周期钩子中,我们使用 createEmbeddedView
方法将模板实例化,并通过 element.nativeElement.querySelectorAll
方法获取生成的 HTML 元素。然后,我们可以遍历这些元素并对它们进行任何操作。
请注意,我们还需要通过构造函数注入 ViewContainerRef
对象,并将其保存在 viewContainerRef
变量中,以便在 ngAfterViewInit
方法中使用。