我正在尝试根据在@Component之前导入的模块属性设置templateUrl
,即
import { details } from './details';
@Component({
selector: 'app-my-cmp',
templateUrl: details.typeA ? './pageA.html' : './pageB.html'
})
在做出错误提示时-Module not found
,
但是,当我在ngOnInit()
中使用导入的模块时,可以访问该模块。
如何在templateUrl
行中使用导入的模块?
答案 0 :(得分:2)
只是另一种解决方案。
您可以使用ng-template
实现此目的,然后根据您的情况相应地动态更新模板-
import {
Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
ViewContainerRef
} from '@angular/core';
@Component({
selector: 'my-app',
template: `<ng-container #vc></ng-container>`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
@ViewChild('vc', {read: ViewContainerRef}) vc;
conditionValue = 'myCondition';
constructor(
private _compiler: Compiler,
private _injector: Injector,
private _m: NgModuleRef<any>
) {
}
ngOnInit() {
let tmpCmp;
if (this.conditionValue === 'myCondition') {
tmpCmp = Component({
templateUrl: './e.html'})(class {
});
} else {
// something else
}
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.vc.insert(cmpRef.hostView);
})
}
}
有关更多信息,请参考-