Angular2 How to clean up the AppModule

10,255

You need to learn to make use of modules.

I usually break the modules down into these types

  • Layout modules
  • Feature modules
  • Core module (only 1)
  • Shared module (only 1)
  • App module (only 1)

Layout module is for laying out the app. For example a topbar module, a sidemenu module, a footer module, and a main content module.

Feature module. What exactly is this? There's really no clear definition, but whatever feature area you feel can be self contained in module, you might as well do it. You will import these feature modules into your layout modules, as the features are what make up the different layout components

Core module. Here you will export your layout modules, and all your core (singleton) services. You only need to export (and not import) the modules, as nothing in the core module will actually use those layout modules. You just export them so that the app module can use them. The core module will only be imported into the app module

Shared module. This is where you will declare all your shared pipes, directives, and components. Also you you can export commonly used modules like CommonModule and FormsModule. Other modules will be using the module

App module. You already know what this is. Out of your own created modules, the only ones you need to import are the shared and core modules.

Here's a basic layout

SharedModule

@NgModule({
  declarations: [ HighlightDirective, SharedPipe, SharedComponent ],
  exports: [ 
    HighlightDirective, SharedPipe, SharedComponent,
    CommonModule, FormsModule
  ]
})
class SharedModule {}

Layout Modules Notice other modules will use the SharedModule

@NgModule({
  imports: [ FeatureAModule, FeatureBModule, SharedModule ]
  declarations: [ TopbarComponent ],
  exports: [ TopbarComponent ]
})
class TopbarModule {}

@NgModule({
  imports: [ SharedModule ]
  declarations: [ SidemenuComponent ],
  exports: [ SidemenuComponent ]
})
class SidemenuModule {
  static forRoot() {   // pattern for adding app-wide services
    return {
      ngModule: SidemenuModule,
      providers: [ MenuSelectionService ]
    }
  }
}

@NgModule({
  imports: [ HomeModule, OtherModule, SharedModuel ]
  declarations: [ MainContentComponent ],
  exports: [ MainContentComponent ]
})
class MainContentModule {}

CoreModule Bring together all the layout modules that make up the application. And also add other app-wide services, that are not tied to other modules

@NgModule({
  imports: [ SidemeuModule.forRoot() ]
  exports: [ TopbarModule, SidemenuModule, MainContentModule ],
})
class CoreModule {
  static forRoot() {
    return {
      ngModule: CoreModule,
      providers: [ UserService, AuthService ]
    }
  }
}

AppModule

@NgModule({
  imports: [
    BrowserModule,
    SharedModule,
    CoreModule.forRoot(),  // forRoot so we get all the providers
    HttpModule,
    RouterModule.forRoot(APP_ROUTES)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
class AppModule {}

See Also:

Share:
10,255
Glenn Sampson
Author by

Glenn Sampson

Updated on June 05, 2022

Comments

  • Glenn Sampson
    Glenn Sampson almost 2 years

    I've been using the tutorials online and created an 'ok' SPA data entry application.

    I have it connecting to my WEB API fine but have only built out one Model and already my AppModule has quiet a few lines.

    I'm thinking forward and using the current method I think the AppModule will be a crazy size once i finish with it, tough to read and possibly even tougher to debug.

    Have I possibly missed the point of how to structure an Angular2 larger application?

    I'm struggling to find a tutorial/project online that is larger than 1 component for reference.

    Below is my app.module.ts and folder structure.

    I separate my CashMovement, ListComponent and DataService which I would think is good practice but add another 10 different data-services and lists and the app.module will be lengthy.

    Before I proceed any further does anybody please have some reading they could point me towards or advice which I understand is subjective to personal opinion.

    app.module

    import './rxjs-operators';
    
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { HttpModule }    from '@angular/http';
    
    import { PaginationModule, DatepickerModule, Ng2BootstrapModule, ModalModule, ProgressbarModule, TimepickerModule } from 'ng2-bootstrap/ng2-bootstrap';
    
    import { SlimLoadingBarService, SlimLoadingBarComponent } from 'ng2-slim-loading-bar';
    
    
    import { AppComponent }   from './app.component';
    import { DateFormatPipe } from './shared/pipes/date-format.pipe';
    import { HighlightDirective } from './shared/directives/highlight.directive';
    import { HomeComponent } from './home/home.component';
    import { MobileHideDirective } from './shared/directives/mobile-hide.directive';
    
    import { CashMovementListComponent } from './cashmovements/cashmovement-list.component';
    import { CashMovementDataService } from './cashmovements/cashmovement.data.service';
    
    import { routing } from './app.routes';
    
    import { ConfigService } from './shared/utils/config.service';
    import { ItemsService } from './shared/utils/items.service';
    import { MappingService } from './shared/utils/mapping.service';
    import { NotificationService } from './shared/utils/notification.service';
    
    @NgModule({
        imports: [
            BrowserModule,
            DatepickerModule,
            FormsModule,
            HttpModule,
            Ng2BootstrapModule,
            ModalModule,
            ProgressbarModule,
            PaginationModule,
            routing,
            TimepickerModule
        ],
        declarations: [
            AppComponent,
            DateFormatPipe,
            HighlightDirective,
            HomeComponent,
            MobileHideDirective,
            SlimLoadingBarComponent,
            CashMovementListComponent        
        ],
        providers: [
            ConfigService,
            CashMovementDataService,
            ItemsService,
            MappingService,
            NotificationService,
            SlimLoadingBarService
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Folder Structure

    enter image description here

  • Nicole Naumann
    Nicole Naumann about 7 years
    Hi peeskillet, I have some model (entity) classes that are used in several feature modules and the core module itself (for example, the user.model.ts), how do I use (import) the user.model.ts in other feature components?
  • Paul Samsotha
    Paul Samsotha about 7 years
    @NicoleNaumann models can go anywhere. Jut put them somewhere convenient. You should have no problem importing them. They have no place in the Angular framework. Use them however you please. There is no real convention on where they should go. Just have it make sense
  • Nicole Naumann
    Nicole Naumann about 7 years
    yes I moved the models to core module, nothing bad happened. Thanks!
  • Jonas Praem
    Jonas Praem over 6 years
    you don't export class x {} ? why is that
  • Paul Samsotha
    Paul Samsotha over 6 years
    @JonasPraem because these are "snippets" not complete code.