代码之家  ›  专栏  ›  技术社区  ›  Patricio Vargas

基于角度条件加载ngModule及其组件

  •  15
  • Patricio Vargas  · 技术社区  · 6 年前

    我是angular方面的新手,我想知道是否有可能根据应用程序上的条件加载和模块及其组件。或者在哪里做这件事是最好的。

    基本上我想做一些事情,比如:

    if(user.deparment === 'coms') {
      //Use the communications.module and its components
    }
    

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

    应用程序。模块图片 enter image description here

    通信。模块图片 enter image description here

    2 回复  |  直到 6 年前
        1
  •  24
  •   Tomasz Kula    6 年前

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

    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);
      }
    }
    

    Live demo

        2
  •  1
  •   Raksha Jayaram    6 年前

    模块在应用程序开始时加载。您需要导入组件,并使用所需的任何组件。您需要将组件注册到模块,以便可以访问组件。