Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load ngModule and its components based on conditional in Angular

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 enter image description here

Communications.module picture enter image description here

like image 691
Patricio Vargas Avatar asked Apr 10 '18 21:04

Patricio Vargas


People also ask

What is the difference between NgModule and component?

This root NgModule is what's used to bootstrap the Angular application. It is in this root module that we also bootstrap the root-level component. This root-level component is the application's main view, which hosts other components for the application. An NgModule is a class adorned with the @NgModule decorator.

What kind of components can be included in exports of @NgModule?

You can export any declarable class —components, directives, and pipes— whether it's declared in this NgModule or in an imported NgModule. You can re-export entire imported NgModules, which effectively re-export all of their exported classes. An NgModule can even export a module that it doesn't import.

How does NgModules work and its components?

@NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them.

How many types of NgModule are there?

There are two types of modules, root modules and feature modules.


1 Answers

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

like image 80
Tomasz Kula Avatar answered Sep 29 '22 14:09

Tomasz Kula