6

我想将 ng-template 的 innerHTML 放到我的组件中。就像是

HTML

<my-comp [template]="myTemplate"></my-comp>
<ng-template #myTemplate></ng-template> 

TS

export class MyComponent implements OnInit {

  @Input() template: string | TemplateRef<any>;

  ngOnInit(){
    console.log(this.template);
  }

}
4

2 回答 2

3

由于您只需要一个将注入模板的外壳,因此请考虑使用指令而不是组件。

@Directive({
  selector: '[template-host]'
})
export class HostDirective{

  @Input('template-host') set templateHtml(value){
    this.hostElement.innerHTML = value;
  }

  private hostElement:HTMLElement;

  constructor(elementRef:ElementRef){
    this.hostElement = elementRef.nativeElement;
  }
}

现在您可以将该指令应用于任何元素,并且提供的template-host绑定将导致该元素中的 html 注入。例如:

<!-- The div will contain the html in myTemplate -->
<div [template-host]="myTemplate"></div>

现场演示

如果您的班级实际上有一个模板,但您只想将 html 注入该模板的一部分,请了解嵌入

于 2017-11-10T17:45:01.140 回答
2

我今天需要解决完全相同的问题并发现了这个问题。我最终研究了 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;
}

希望有帮助!

于 2018-05-08T13:54:57.977 回答