Blog>
Snippets

Organizing Application Code Structure with NgModules

Illustrate how to use NgModules to organize application code into cohesive blocks, focusing on a modular approach that separates concerns and functionality.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Defines the root module, AppModule, which is the entry point for an Angular application. It imports BrowserModule, which is required when running the application in the browser, and declares the root component, AppComponent. No providers are defined at this level, and the bootstrap array tells Angular to start the application with the AppComponent.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  declarations: [
    FeatureComponent
  ],
  imports: [
    CommonModule
  ],
  providers: [],
  exports: [FeatureComponent]
})
export class FeatureModule { }
Defines a feature module, FeatureModule, which groups relevant components, directives, and pipes that belong to a specific application feature. In this case, FeatureComponent is declared. This module imports CommonModule, containing common directives like NgIf and NgFor. No providers are defined, and FeatureComponent is exported so it can be used in other modules.
import { NgModule } from '@angular/core';
import { LoginComponent } from './login.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [LoginComponent],
  imports: [FormsModule],
})
export class LoginModule { }
Creates a LoginModule which focuses on the login functionality of the application. It declares the LoginComponent and imports FormsModule to work with template-driven forms. This allows us to create forms and bind them to the component's data model.