Alex Leibovich Alex Leibovich - 2 months ago 15
TypeScript Question

Importing a lot of modules in Angular

I'm building an app with Angular 4 and Angular Material, each Material directive requires me to import its module separately..

For example, i'm building a navigation bar, this is how the

nav.module.ts
starts to look like:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {NavComponent} from './nav.component';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { MdInputModule } from '@angular/material';
import { MdMenuModule } from '@angular/material';
import {MdButtonModule} from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

@NgModule({
imports: [
CommonModule,
AngularFontAwesomeModule,
MdInputModule,
MdMenuModule,
MdButtonModule,
FlexLayoutModule,
HttpClientModule,

....


There are only 3 Material modules right now, i will need to add more later and except Material, there are also other modules that need to be imported...

Just started moving from AngularJS to Angular4 it feels to me like i'm doing something wrong... Is there a better way to import all the modules? Is my approach to structuring the app is wrong?

Answer Source

You can create a "shared" module that exports each of the Material Design modules that you need. Then you can simply import the "shared" module into your other modules that need them.

Here is an example:

enter image description here

In this picture I have a shared module that is exporting CommonModule and FormsModule. The ProductModule then imports the SharedModule to get all of the functionality provided by the CommonModule and FormsModule.

I have a youtube video about this here: https://www.youtube.com/watch?v=ntJ-P-Cvo7o