问题是ng-template
必须编译。理解为什么要阅读以下是您需要了解的有关 Angular 动态组件的知识 https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e.
现在,模板只能作为组件的一部分进行编译。因此,您需要使用此模板定义一个组件,然后您可以使用以下方式访问此模板工厂viewChild
或指令。和viewChild
你依赖生命周期挂钩和变更检测 https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f所以我会采用指导性方法。这是伪代码:
@Component() {
template: '<ng-template requestor>...</ng-template>'
}
class NgTemplateProviderComponent {
t: TemplateRef;
register(t) {
this.t = t;
}
}
@Directive() {
selector: 'requestor;
}
class TemplateRequestor {
constructor(t: TemplateRef, p: NgTemplateProviderComponent) {
p.register(t);
}
}
要了解有关使用指令读取 templateRef 的这种方法的更多信息以下是在评估 @ViewChild 查询之前如何获取 ViewContainerRef https://blog.angularindepth.com/here-is-how-to-get-viewcontainerref-before-viewchild-query-is-evaluated-f649e51315fb.
然后,您需要访问NgTemplateProviderComponent
组件工厂,创建其实例以获取templateRef
:
class SomeComponent {
constructor(r: ComponentFactoryResolver, i: Injector) {
const f = r.resolveComponentFactory(NgTemplateProviderComponent);
const templateRef =f.create(i).instance.t;
}
}
只有这样你才能使用ngTemplateOutlet
渲染模板的指令。