本文介绍了基于Angular中的条件加载ngModule及其组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是angular的新手,我想知道是否有可能基于app.module的条件来加载和模块化我制作的组件及其组件,或者这是在哪里做的最好的地方.
I'm new in angular and I was wondering if it's possible to load and module and its components I made based on a conditional on the app.module or where would it be the best place to do this.
基本上我想做类似的事情:
Basically I want to do something like:
if(user.deparment === 'coms') {
//Use the communications.module and its components
}
我附上了一些图片,以便大家看到应用程序的结构.如有必要,我可以添加代码而不是图片.
I have attached some picture so you guys can see the structure of the app. if necessary I can add the code instead of a picture.
应用模块图片
Communications.module图片
Communications.module picture
推荐答案
您可以执行简单的三元检查以有条件地导入模块.像这样:
You can do a simple ternary check to conditionally import a module. Like this:
import { NgModule, Optional } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({}) class MyModule {}
// toggle and watch the console
const production = true;
@NgModule({
imports: [ BrowserModule, production ? MyModule : []],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
constructor(@Optional() module: MyModule) {
console.log(module);
}
}
这篇关于基于Angular中的条件加载ngModule及其组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!