typescript 带有字符串变量的 Angular 2 动态模板 url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47133024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:00:55 来源:igfitidea点击:
Angular 2 dynamic template url with string variable?
提问by Dell
@Component({
selector: 'bancaComponent',
templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
str: String;
constructor(private http: Http) { }
ngOnInit(): void {
this.str = "./file.component.html";
}
Is there another way to make it ? Thanks :)
还有另一种方法吗?谢谢 :)
回答by Boulboulouboule
Try this solution :
试试这个解决方案:
import {
Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';
@Component({
selector: 'bancaComponent',
template: `
<ng-container #dynamicTemplate></ng-container>
`
// or with a templateUrl
})
export class BancaComponent implements AfterViewInit, OnInit {
@ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;
constructor(private _compiler: Compiler,
private _injector: Injector,
private _m: NgModuleRef<any>) {
}
ngAfterViewInit() {
let myTemplateUrl = './file.component.html';
if (MYCONDITION === MAEXPECTATION) {
myTemplateUrl = './another-template.component.html';
}
const tmpCmp = Component({
moduleId: module.id, templateUrl: myTemplateUrl
})(class {
});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {
});
this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = f.create(this._injector, [], null, this._m);
cmpRef.instance.name = 'dynamic';
this.dynamicTemplate.insert(cmpRef.hostView);
});
}
}
Inspired from : Angular 2/4 component with dynamic template or templateUrl
灵感来自:带有动态模板或 templateUrl 的 Angular 2/4 组件
Official source : https://angular.io/guide/dynamic-component-loader