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
- Declarations: List of components, directives, and pipes that belong to this module
- Imports: Other modules that this module needs
- Providers: Services that will be available to the entire application
- 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
- Shared Module: For commonly used components, directives, and pipes
- Core Module: For singleton services and single-load components
- Feature Modules: For distinct features of your application
- Routing Modules: For managing navigation between pages
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.