Modules
Modules
Section titled βModulesβWhat it means
Section titled βWhat it meansβNgModule was historically how Angular grouped related components, directives, pipes, and services, and declared what a section of the app depended on. Since Angular 14+, standalone components (each component declares its own imports directly) have become the default and recommended approach, and new projects no longer need a root AppModule at all β but a huge amount of existing Angular code still uses NgModule, so understanding it remains important.
Examples
Section titled βExamplesβ// Older NgModule-based approach@NgModule({ declarations: [UserListComponent, UserCardComponent], imports: [CommonModule, FormsModule], exports: [UserListComponent],})export class UserModule {}
// Modern standalone approach (Angular 14+, the current default)@Component({ selector: 'app-user-list', standalone: true, // no NgModule needed imports: [CommonModule, UserCardComponent], // component declares its own dependencies template: `...`,})export class UserListComponent {}
// Bootstrapping without any AppModule at allbootstrapApplication(AppComponent, { providers: [provideRouter(routes), provideHttpClient()],});Common mistake
Section titled βCommon mistakeβAssuming a standalone component automatically has access to another component/directive/pipe just because itβs used elsewhere in the app β standalone components must explicitly list every dependency in their own imports array; nothing is implicitly shared the way NgModule declarations were.
@Component({ selector: 'app-dashboard', standalone: true, imports: [CommonModule], // forgot to import DatePipe or CurrencyPipe! template: `{{ total | currency }}`, // Error: 'currency' pipe not found})export class DashboardComponent {}
// Fix: explicitly import what this component uses@Component({ selector: 'app-dashboard', standalone: true, imports: [CommonModule], // CommonModule includes CurrencyPipe, DatePipe, etc. template: `{{ total | currency }}`,})Quick practice
Section titled βQuick practiceβ-
Whatβs the recommended approach for new Angular components since Angular 14+?
Answer
Standalone components, which declare their ownimportsdirectly and don't require being declared inside anNgModule. -
Does a standalone component automatically get access to directives/pipes used elsewhere in the app?
Answer
No β each standalone component must explicitly list every directive, pipe, and component it uses in its ownimportsarray. -
Do new Angular projects still require a root
AppModule?Answer
No β modern Angular apps can bootstrap directly from a standalone root component usingbootstrapApplication(), with providers configured via functions likeprovideRouter()instead of anNgModule.