Angular — Standalone Components
What are Standalone Components?
Standalone components don't need NgModules — they declare their own dependencies.
Basic Standalone Component
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-hello',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<input [(ngModel)]="name">
<p>Hello, {{name}}!</p>
`
})
export class HelloComponent {
name = '';
}
Standalone with Routing
const routes: Routes = [
{
path: '',
loadComponent: () => import('./home/home.component')
.then(m => m.HomeComponent)
}
];
Standalone Directive
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
constructor() {
inject(ElementRef).nativeElement.style.backgroundColor = 'yellow';
}
}
Standalone Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse',
standalone: true
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
Benefits
- No NgModule boilerplate
- Easier to understand
- Better tree-shaking
- Simpler dependency management
Mini Practice
- Create a standalone component
- Use standalone directive
- Create standalone pipe
- Lazy load standalone components
Up Next
Continue with Lazy Loading — lazy loading routes.
Related Topics
Frequently Asked Questions about Standalone Components
What is Standalone Components in Angular?
Standalone Components is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Standalone Components?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Standalone Components.
Why is Standalone Components important in Angular?
Standalone Components is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.