How to get ng-template innerHTML to component

Sibiraj picture Sibiraj · Nov 10, 2017 · Viewed 8.7k times · Source

I want to get the innerHTML of ng-template to my component. Something like

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);
  }

}

Answer

BeetleJuice picture BeetleJuice · Nov 10, 2017

Since you only require a shell into which a template will be injected, consider using a Directive instead of a component.

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

Now you can apply that directive to any element, and the provided template-host binding will cause html injection in that element. For example:

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

Live demo

If your class actually has a template, but you want to inject html into only a portion of that template, learn about transclusion