Javascript 在@Component中使用导入的模块
我正在尝试根据在@Component之前导入的模块属性设置Javascript 在@Component中使用导入的模块,javascript,angular,angular6,Javascript,Angular,Angular6,我正在尝试根据在@Component之前导入的模块属性设置templateUrl,即- import { details } from './details'; @Component({ selector: 'app-my-cmp', templateUrl: details.typeA ? './pageA.html' : './pageB.html' }) 当我这样做时,我得到一个错误-模块未找到, 但是,当我在ngOnInit()中使用导入的模块时,我可以访问此模块 如何使用t
templateUrl
,即-
import { details } from './details';
@Component({
selector: 'app-my-cmp',
templateUrl: details.typeA ? './pageA.html' : './pageB.html'
})
当我这样做时,我得到一个错误-模块未找到
,
但是,当我在ngOnInit()
中使用导入的模块时,我可以访问此模块
如何使用templateUrl
行中导入的模块 这只是另一个解决方案
您可以使用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);
})
}
}
导入{
编译器、组件、注入器、版本、ViewChild、NgModule、NgModuleRef、,
ViewContainerRef
}从“@angular/core”开始;
@组成部分({
选择器:“我的应用程序”,
模板:``,
样式URL:['./app.component.css']
})
导出类AppComponent{
名称='角度';
@ViewChild('vc',{read:ViewContainerRef})vc;
条件值='myCondition';
建造商(
专用编译器:编译器,
专用注射器:注射器,
私有:NgModuleRef
有关更多信息,请参阅-
尝试将详细信息
分配给变量,然后以三值形式使用该变量