簡體   English   中英

如何將ng-template innerHTML添加到組件

[英]How to get ng-template innerHTML to component

我想將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);
  }

}

由於只需要一個將模板注入其中的外殼程序,因此請考慮使用指令而不是組件。

@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注入該模板的一部分中,請了解轉譯

我今天需要解決完全相同的問題,並找到了這個問題。 我最終查看了ng-bootstrap,以了解它們的工作方式,最終這是一個相當簡單的解決方案。

您需要掌握要插入字符串/ TemplateRef的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;
}

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM