如何将ng-template innerHTML添加到组件 [英] How to get ng-template innerHTML to component
本文介绍了如何将ng-template innerHTML添加到组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将ng-template的innerHTML获取到我的组件中.像
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);
}
}
推荐答案
由于只需要将模板注入其中的外壳,因此请考虑使用指令而不是组件.
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;
}
}
现在您可以将该指令应用于任何元素,并且提供的template-host
绑定将导致该元素中的html注入.例如:
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>
如果您的班级实际上有一个模板,但您只想将html注入该模板的一部分,请了解有关包容的信息
If your class actually has a template, but you want to inject html into only a portion of that template, learn about transclusion
这篇关于如何将ng-template innerHTML添加到组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文