Angular course Β· Module 3: Modules
Standalone Components vs NgModules
In this lesson3
Angular 17+ prefers Standalone Components - a simpler approach without modules.
Comparison of Approaches
Old Way (NgModule-based)
// samurai.component.ts
@Component({
selector: 'app-samurai',
standalone: false,
templateUrl: './samurai.component.html'
})
export class SamuraiComponent { }
// samurai.module.ts
@NgModule({
declarations: [SamuraiComponent],
imports: [CommonModule, SharedModule],
exports: [SamuraiComponent]
})
export class SamuraiModule { }New Way (Standalone)
// samurai.component.ts - everything in one file!
@Component({
selector: 'app-samurai',
standalone: true,
imports: [CommonModule, CardComponent, ButtonComponent],
templateUrl: './samurai.component.html'
})
export class SamuraiComponent { }
// Usage - direct import
@Component({
standalone: true,
imports: [SamuraiComponent]
})
export class AppComponent { }Lazy Loading with Standalone
// app.routes.ts
export const routes: Routes = [
{
path: 'samurai',
loadComponent: () => import('./samurai/samurai.component')
.then(c => c.SamuraiComponent)
},
{
path: 'dojo',
loadChildren: () => import('./dojo/dojo.routes')
.then(r => r.DOJO_ROUTES)
}
];When to Use Which?
| Scenario | Recommendation |
|---|---|
| New project (Angular 17+) | Standalone Components |
| Legacy project | Stay with NgModules |
| Angular library | Standalone (easier to use) |
| Large enterprise project | You can mix both approaches |
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. From which Angular version are Standalone Components the default and recommended approach?
2. Where does a standalone component declare its dependencies (e.g. CommonModule)?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the samurai card component so that it works without an NgModule and brings in CommonModule and RouterLink, which its template uses, by itself.
- Horizontal ordering
Arrange the tokens of the line marking a component as standalone in the decorator:
- Click in order
Click the elements in order to build the start of standalone lazy loading: loadComponent: () =>