I want to dynamically create a component with a dynamic template, so that interpolations of this template will resolve in the context of the dynamic component.
I know that I can use this code to create a dynamic component (which must be mentioned in entryComponents on the module):
My static component:
@Component({
selector: 'html-type',
template: `<ng-template #htmlcontrolcomponent></ng-template>`
})
export class HtmlTypeComponent implements AfterViewInit{
@ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {
super();
}
ngAfterViewInit() {
this.createComponent("<div>{{contextvar}}</div>");
}
createComponent(template) {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
const componentRef = this.entry.createComponent(factory);
componentRef.instance.template = template; // this doesn't work, is there a way to do it?
}
Component that should be dynamically added:
import { Component} from '@angular/core';
@Component({
selector: 'html-control',
template: '',
})
export class HtmlControlComponent {
contextvar: string = "This is my current context";
}
Is there a way to reassign the template of a dynamically created component?
What I wanted to achieve: The template of the dynamic component should be dynamic (entered by user and sanitized)