Load ngModule and its components based on conditional in Angular

别来无恙 提交于 2019-11-29 11:53:46

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

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.

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