Modules

Basic modules, recommendation

Components (10 minutes)

Modules: Code Organization

Modules in Angular help organize related code into cohesive blocks of functionality. They are decorated with @NgModule.

Module Structure

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent    // Components must be declared in a module
  ],
  imports: [
    BrowserModule         // Other modules we want to use
  ],
  providers: [],          // Services for dependency injection
  bootstrap: [AppComponent] // Root component to start with
})
export class AppModule { }

Key Module Concepts

  1. Declarations: List of components, directives, and pipes that belong to this module
  2. Imports: Other modules that this module needs
  3. Providers: Services that will be available to the entire application
  4. Bootstrap: The main application view (root component)

Feature Modules

For better organization, you can create feature modules:

ng generate module feature-name

Example structure:

@NgModule({
  declarations: [FeatureComponent],
  imports: [
    CommonModule,
    FeatureRoutingModule
  ],
  exports: [FeatureComponent]  // Make components available to other modules
})
export class FeatureModule { }

Evaluation Question

Q: “To add a new page, do you create a component or a module? Why?”

A: The answer depends on your needs:

  • Create a Component if you’re adding a single new page/view
  • Create a Module if you’re adding a feature with multiple related components, services, and routes

Best practices:

  • Components for individual pages/features
  • Modules for grouping related functionality
  • Feature modules for lazy loading and better organization

Common Patterns

  1. Shared Module: For commonly used components, directives, and pipes
  2. Core Module: For singleton services and single-load components
  3. Feature Modules: For distinct features of your application
  4. Routing Modules: For managing navigation between pages

Last modified March 27, 2025: Edit members.yaml (21070ed)