我正在尝试从数据库动态加载组件的模板,我所拥有的是以下HTML模板
<h1>{{tname}}</h1>
我尝试了Angular official Doc中提到的两种方法,第二次使用createEmbeddedView()
上调用的ViewContainerRef
我确实获得了应用了h1
代码的模板结果,但模板未呈现。我得到 {{tname}}
我在组件的模板中:
<div #target></div>
<ng-template #template>
<div [innerHTML]="templateString"></div>
</template>
我也尝试过:
<div #target></div>
<ng-template #template let-tname="fromContext">
<div [innerHTML]="templateString"></div>
</template>
我的问题是:
@Component
装饰器的模板的值吗?修改 组件代码:
@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;
}
}