Blog>
Snippets

Organizing Angular Modules

Provide an example of organizing Angular modules for better code separation and maintainability.
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SharedModule } from './shared/shared.module';
import { FeatureModule } from './feature/feature.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule,
    FeatureModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
This is the root module of an Angular application where all the other modules are imported. We've separated our feature-specific code into 'FeatureModule' and our reusable code into 'SharedModule'.
// shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  exports: []
})
export class SharedModule { }
The SharedModule contains components, directives, and pipes that are used across different parts of the application. It imports CommonModule because it will be used across many other modules.
// feature.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
import { FeatureService } from './feature.service';

@NgModule({
  declarations: [
    FeatureComponent
  ],
  imports: [
    CommonModule
  ],
  providers: [
    FeatureService
  ]
})
export class FeatureModule { }
This is an example of a feature module which might contain all the components, services, and other dependencies tied to a specific feature of the application. It also imports CommonModule as features might have templates.