在Angular中,您可以使用ViewChild装饰器来访问位于ng-template中的引用变量。
首先,在你的组件类中引入ViewChild装饰器和模板引用变量:
import { Component, ViewChild, TemplateRef } from '@angular/core';
然后,在你的组件类中使用ViewChild装饰器来获取ng-template中的引用变量:
@Component({
selector: 'app-example',
template: `
Template content
`
})
export class ExampleComponent {
@ViewChild('myTemplate', { static: true }) myTemplate: TemplateRef;
// ...
}
在上面的示例中,我们创建了一个名为myTemplate
的模板引用变量,并使用ViewChild
装饰器将其赋值给myTemplate
属性。
现在,您可以在组件类中的其他方法中使用myTemplate
属性来访问ng-template中的内容:
export class ExampleComponent {
@ViewChild('myTemplate', { static: true }) myTemplate: TemplateRef;
ngAfterViewInit(): void {
const viewRef = this.myTemplate.createEmbeddedView(null);
console.log(viewRef.rootNodes[0].textContent); // 输出:Template content
}
}
在上面的示例中,我们在ngAfterViewInit
方法中使用myTemplate
属性创建了一个嵌入视图,并通过viewRef.rootNodes[0]
访问了ng-template中的内容。
请注意,我们需要将static
选项设置为true
,以便在视图初始化期间访问模板引用变量。
希望这可以帮助到您!