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