Importing a lot of modules in Angular

2019-04-13 04:33发布

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?

1条回答
不美不萌又怎样
2楼-- · 2019-04-13 05:10

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

查看更多
登录 后发表回答