Load ngModule and its components based on conditional in Angular

偶尔善良 提交于 2020-01-20 06:58:25

问题


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.

App.module picture

Communications.module picture


回答1:


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

Live demo




回答2:


Modules are loaded at the start of your application. You need to import the components, and use whichever component you need. You need to register your component to a module, so that your component is accessible.



来源:https://stackoverflow.com/questions/49762835/load-ngmodule-and-its-components-based-on-conditional-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!