The Pragmatic Guide to Angular Standalone Architecture
Standalone Architecture: Ditch modules completely; your components, directives, and pipes now stand proudly on their own.
In legacy Angular, every component, directive, and pipe needed an NgModule to act as its broker. Want to use a button inside a card? You had to declare it in a module, export it from that module, and import that module somewhere else.
Standalone architecture cuts out this boilerplate. Components, directives, and pipes now declare and manage their dependencies directly where they are used.
## 1. Traditional NgModule vs. Modern Standalone
| Concept | Traditional NgModule | Modern Standalone |
| --- | --- | --- |
| Component Setup | Registered in a module's declarations: [...] | Configured directly with imports: [...] in the decorator |
| Dependencies | Bulky shared bundles (SharedModule) | Fine-grained, component-level imports |
| App Startup | platformBrowserDynamic().bootstrapModule(AppModule) | Direct root mount: bootstrapApplication(AppComponent) |
| Lazy Loading | Feature module files (*.module.ts) | Direct component (loadComponent) or route file imports |
| Tree-Shaking | Coarse: importing a module pulls in unused siblings | Precise: the bundler drops anything not directly imported |
## 2. Core Standalone Primitives
### 2.1 Standalone Component
Instead of relying on a parent module to supply template helpers (like *ngIf, *ngFor, or custom pipes), dependencies live right inside the component's imports array.
```ts
// src/app/user-card/user-card.component.ts
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common'; // Or use Angular's built-in @if / @for syntax
@Component({
selector: 'app-user-card',
standalone: true,
imports: [CommonModule],
template: `
`
})
export class UserCardComponent {
@Input() user?: { name: string; joinedAt: Date };
}
```
### 2.2 Standalone Directive
Directives plug directly into whatever component needs them without having to travel through a SharedModule.
```ts
// src/app/directives/highlight.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
@Input() appHighlight = 'yellow';
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}
```
### 2.3 Standalone Pipe
Pipes become independent transform functions that any template can grab on demand.
```ts
// src/app/pipes/truncate.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate',
standalone: true
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25): string {
return value.length > limit ? `${value.slice(0, limit)}...` : value;
}
}
```
## 3. Composing Standalone Primitives
When building a dashboard or screen, the host component's imports array acts as an explicit, self-documenting manifest of everything running in that template.
```ts
// src/app/dashboard/dashboard.component.ts
import { Component } from '@angular/core';
import { UserCardComponent } from '../user-card/user-card.component';
import { HighlightDirective } from '../directives/highlight.directive';
import { TruncatePipe } from '../pipes/truncate.pipe';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [
UserCardComponent, // Child component
HighlightDirective, // Attribute directive
TruncatePipe // Pipe
],
template: `
`
})
export class DashboardComponent {
bioText = 'Angular standalone architecture removes the friction of maintaining complex module wiring.';
currentUser = { name: 'Priya Sharma', joinedAt: new Date() };
}
```
## 4. Bootstrapping Without AppModule
Apps start directly with bootstrapApplication(). Instead of importing feature modules into an AppModule, configure global runtime concerns—such as the router and HTTP client—using functional provider helpers.
```ts
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { APP_ROUTES } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
// Wire the router and automatically bind route params to @Input props
provideRouter(APP_ROUTES, withComponentInputBinding()),
// Functional replacement for HttpClientModule
provideHttpClient()
]
}).catch(err => console.error(err));
```
## 5. Lean Routing and Lazy Loading
You no longer need to write a wrapper module just to lazy-load a route.
loadComponent: Lazy-loads an individual standalone component file.
loadChildren: Lazy-loads a simple routes.ts file containing child routes.
```ts
// src/app/app.routes.ts
import { Routes } from '@angular/router';
export const APP_ROUTES: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'dashboard'
},
{
path: 'dashboard',
// Dynamically imports only this component bundle on demand
loadComponent: () =>
import('./dashboard/dashboard.component').then(m => m.DashboardComponent)
},
{
path: 'admin',
// Pulls in child routes without needing an AdminModule
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
}
];
```
## 6. Dependency Injection & Service Scopes
Dependency injection still functions the same way under the hood, but scope boundaries map cleanly to components and routes:
```text
[ Root Singleton ] @Injectable({ providedIn: 'root' })
│
[ Route Scope ] providers: [CheckoutService] in APP_ROUTES
│
[ Component Scope ] providers: [WidgetService] in @Component
```
- **Root Scope (providedIn:** 'root'): One shared instance lives across the entire app lifecycle.
- **Route Scope:** Provided in route definitions via providers: [...]. The instance initializes when the user navigates into the route branch and is torn down when they leave.
- **Component Scope:** Provided in the @Component(\{ providers: [...] \}) array. A fresh instance is created for that component instance and destroyed when it unmounts.
## 7. Migration & Interoperability
You do not need to rewrite an entire app to use standalone features. Standalone components and legacy NgModule setups can talk to each other without issues:
Using a legacy NgModule in a standalone component: Drop the module directly into the component's imports array:
```ts
@Component({
standalone: true,
imports: [MatButtonModule], // Legacy module imported directly
/* ... */
})
```
Using a standalone component in a legacy NgModule: Put the standalone component in the module's imports array—never in declarations:
```ts
@NgModule({
imports: [UserCardComponent], // Standalone components are imported, not declared
})
export class LegacyFeatureModule {}
```
To migrate an entire project automatically, run Angular's built-in schematic:
```bash
ng generate @angular/core:standalone
```
- **The CLI steps through three phases:** converting your components, removing obsolete modules, and finally switching your main.ts over to bootstrapApplication.
{{ user.name }}
Joined: {{ user.joinedAt | date:'mediumDate' }}
Dashboard Overview
{{ bioText | truncate: 50 }}
