I am trying to load a component's template dynamically from database, what I have is the following HTML Template
<h1>{{tname}}</h1>
I tried two methods one mentioned in Angular official Doc and second using createEmbeddedView()
called on ViewContainerRef
I do get the template results withh1
tag applied but the template is not rendered. I get {{tname}}
I have inside the component's template:
<div #target></div>
<ng-template #template>
<div [innerHTML]="templateString"></div>
</template>
I also tried:
<div #target></div>
<ng-template #template let-tname="fromContext">
<div [innerHTML]="templateString"></div>
</template>
My questions are:
- How would I render the template, with supplied data?
- Can I set the Component's template dynamically i.e the value of template supplied to the
@Component
decorator?
Edit Component's Code:
@Component({
selector: 'app-print-receipt-template-preview',
templateUrl: './print-receipt-template-preview.component.html',
styleUrls: ['./print-receipt-template-preview.component.scss']
})
export class PrintReceiptTemplatePreviewComponent implements OnInit {
private _tmp:string;
private _data:any;
@Input()
set template(v:string) {
if (v) {
this._tmp = v;
this.initTemplate()
}
}
get template() {
return this._tmp;
}
@Input()
set saleData(v:any) {
this._data = v;
}
get saleData() {
return this._data;
}
@ViewChild('receiptContainer', {read: ViewContainerRef}) private target: ViewContainerRef;
@ViewChild('template',{read: TemplateRef}) private tmp: TemplateRef<any>;
constructor(private componentResolver: ComponentFactoryResolver) { }
ngOnInit() {
}
initTemplate() {
// let cmp = PrintReceiptTemplateComponent;
// let fac = this.componentResolver.resolveComponentFactory(cmp);
this.target.clear();
let componentRef = this.target.createEmbeddedView(this.tmp, {saleData: this._data});
// let instance:any = componentRef.instance;
// instance.data = this._data;
// instance.template = this._tmp;
}
}