如何将ng-template innerHTML转换为组件

时间:2017-11-10 17:12:04

标签: angular typescript ng-template

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

}

2 个答案:

答案 0 :(得分:2)

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

@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>

Live demo

如果您的班级实际上有模板,但您想将html仅注入该模板的一部分,learn about transclusion

答案 1 :(得分:-1)

我今天需要解决完全相同的问题并找到了这个问题。我最终研究了ng-bootstrap,看看他们是如何做到的,最终这是一个相当简单的解决方案。

您需要获取希望将字符串/ TemplateRef插入的ViewContainerRef。这可以是host元素(在构造函数中注入ViewContainerRef)或ViewChild。 e.g:

constructor(private viewContainerRef: ViewContainerRef) { }

@ViewChild('someDiv', {read: ViewContainerRef}) viewContainerRef: ViewContainerRef;

接下来,在ngOnInit()中你需要做一个if / else,取决于输入是否为TemplateRef或string,并将其分配给viewContainerRef:

if (this.template instanceof TemplateRef) {
   this.viewContainerRef.createEmbeddedView(<TemplateRef<any>>this.template);
} else {
    this.viewContainerRef.element.nativeElement.innerHTML = this.template;
}

希望有所帮助!

相关问题