Angular Best Practices & Standalone Components
Writing clean, optimized Angular code ensures high performance, small bundle sizes, and maintainability. In this lesson, we will look at Angular best practices and standalone components.
1 OnPush Change Detection and Standalone components
Key optimizations for modern Angular include:
- Standalone Components: Introduced in Angular 14+, standalone components eliminate the need for NgModules. They are self-contained and import their dependencies directly:
standalone: true. - ChangeDetectionStrategy.OnPush: Optimizes performance by checking component templates for updates only when input values (@Input) change or events are fired, rather than running change detection globally.
- Lazy Loading Components: Dynamically import routes in your routing configuration to reduce initial bundle size.
2 Writing a Standalone Component
Let's check how to declare a standalone component using OnPush change detection:
TypeScript — Standalone Component
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-avatar',
standalone: true, // standalone declaration
imports: [CommonModule], // imports dependencies directly
template: `![User avatar]()
3 Code Challenge
Challenge: Write a routing configuration that lazy-loads a standalone dashboard component using the
loadComponent property instead of component.