我今天需要解决完全相同的问题并发现了这个问题。我最终研究了 ng-bootstrap 以了解他们是如何做到的,最终这是一个相当简单的解决方案。
您需要获取要插入字符串/模板引用的 ViewContainerRef。这可以是宿主元素(在构造函数中注入的 ViewContainerRef)或 ViewChild。例如:
constructor(private viewContainerRef: ViewContainerRef) { }
或者
@ViewChild('someDiv', {read: ViewContainerRef}) viewContainerRef: ViewContainerRef;
接下来,在 ngOnInit() 中,您需要根据输入是 TemplateRef 还是字符串来执行 if/else 并将其分配给 viewContainerRef:
if (this.template instanceof TemplateRef) {
this.viewContainerRef.createEmbeddedView(<TemplateRef<any>>this.template);
} else {
this.viewContainerRef.element.nativeElement.innerHTML = this.template;
}
希望有帮助!