如何将 ng-template innerHTML 获取到组件

Sib*_*raj 6 typescript ng-template angular

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

HTML

<my-comp [template]="myTemplate"></my-comp>
<ng-template #myTemplate></ng-template> 
Run Code Online (Sandbox Code Playgroud)

TS

export class MyComponent implements OnInit {

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

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

}
Run Code Online (Sandbox Code Playgroud)

Bee*_*ice 3

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

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

<!-- The div will contain the html in myTemplate -->
<div [template-host]="myTemplate"></div>
Run Code Online (Sandbox Code Playgroud)

现场演示

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