基于Angular中的条件加载ngModule及其组件

dev*_*ato 3 angular-module angular

我是angular的新手,我想知道是否可以加载和基于我在app.module上创建的模块及其组件,或者在哪里是最佳选择

基本上我想做这样的事情:

if(user.deparment === 'coms') {
  //Use the communications.module and its components
}
Run Code Online (Sandbox Code Playgroud)

我附上了一些图片,以便你们看到应用程序的结构。如有必要,我可以添加代码而不是图片。

应用模块图片 在此处输入图片说明

Communications.module图片 在此处输入图片说明

Tom*_*ula 5

您可以执行简单的三元检查来有条件地导入模块。像这样:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示

  • 这种方法仅适用于静态值。如果你想配置提供者,你可以使用 `forRoot` 静态方法 https://angular.io/guide/ngmodule-faq#what-is-the-forroot-method (3认同)