How to get ng-template innerHTML to component

穿精又带淫゛_ 提交于 2019-12-05 01:37:30

问题


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

}

回答1:


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




回答2:


I needed to solve exactly the same problem today and found this question. I ended up looking into ng-bootstrap in order to see how they did it, and ultimately it's a fairly simple solution.

You need to get hold of ViewContainerRef that you want your string/TemplateRef to be inserted to. This can be either the host element (ViewContainerRef injected in constructor) or ViewChild. e.g:

constructor(private viewContainerRef: ViewContainerRef) { }

or

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

next, in ngOnInit() you need to do an if/else depending if the input is TemplateRef or string and assign it to viewContainerRef:

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

Hope that helps!



来源:https://stackoverflow.com/questions/47227950/how-to-get-ng-template-innerhtml-to-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!