templateref html内容,angular - Can I create a TemplateRef from a string? - Stack Overflow

In these examples we're not actually "creating" the templateRef, since this would require angular renderer factories and a lot of extra code to create proper Injectors for the new EmbeddedView. And we just need to edit the template on the fly with a string value so here goes.

Example 1: Using ng-container

Template markdown extending the OP's question using ng-container

Then the component's code would look like this

export class Component implements AfterViewInit{

@ViewChild("content") contentRef: TemplateRef;

@ViewChild("container", {read: ViewContainerRef}) containerRef: ViewContainerRef;

divRef: HTMLElement;

value: string = "";

@Input()

set simpleContent(value: string) {

if(this.divRef){

this.divRef.innerHTML = this.value;

}

this.value = value;

}

constructor() {}

ngAfterViewInit(): void {

let div = document.createElement("div");

div.innerHTML = this.value;

var embeddedViewRef = this.contentRef.createEmbeddedView(this.containerRef);

this.containerRef.insert(embeddedViewRef);

embeddedViewRef.rootNodes[0].replaceWith(div);

this.divRef = div;

}

}

In this example we are getting a reference to the ng-content tag located in the rootNodes of the EmbeddedView and replacing it with our native html template string.

Example 2: Using elementRef

Since we're injecting with nativeElements in the first example, i thought why not directly edit the first div tag by getting it's reference with ViewChild and ElementRef.

@Component({

selector: "component",

template:`

})

export class Component implements AfterViewInit{

@ViewChild("ref", {read: ElementRef}) tref: ElementRef;

value: string = "";

@Input()

set simpleContent(value: string) {

if(this.tref) this.tref.nativeElement.innerHTML = this.value;

this.value = value;

}

constructor() {}

ngAfterViewInit(): void {

this.tref.nativeElement.innerHTML = this.value;

}

}

Example 3: Using simple Databinding

And finally since it's just a simple string template we want to inject in the component why not simply use databinding on innerHTML

@Component({

selector: "component",

template:`

})

export class Component{

value: string = "";

@Input()

set simpleContent(value: string) {

this.value = value;

}

constructor() {}

}

After almost 2 years i doubt OP was still waiting for an answer. This reply was mainly a challenge for me but i learned a few things myself doing research. Like this article about dom manipulation techniques in angular

In hope this could be useful to someone out there

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值