Standalone components in Angular
What are Standalone Components?
Standalone components (Angular 14+) are components that don't need to be declared in an NgModule. They manage their own dependencies directly, making Angular apps simpler and more modular.
Traditional vs Standalone
typescript
// ❌ Traditional: Must declare in NgModule
@Component({ selector: 'app-hello' })
export class HelloComponent {}
@NgModule({
declarations: [HelloComponent],
imports: [CommonModule],
exports: [HelloComponent],
})
export class HelloModule {}typescript
// ✅ Standalone: Self-contained
@Component({
selector: 'app-hello',
standalone: true,
imports: [CommonModule], // Import dependencies directly
template: \`
<h1 *ngIf="show">Hello, {{ name }}!</h1>
\`
})
export class HelloComponent {
@Input() name = 'World';
show = true;
}Bootstrapping Without NgModule
typescript
// main.ts — No AppModule needed!
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideHttpClient(),
],
});Using Standalone Components
typescript
// In another standalone component
@Component({
standalone: true,
imports: [HelloComponent, UserCardComponent], // Import other standalone components
template: \`
<app-hello name="Angular" />
<app-user-card [user]="currentUser" />
\`
})
export class DashboardComponent {}Lazy Loading Standalone Components
typescript
// In routes
export const routes: Routes = [
{
path: 'admin',
loadComponent: () => import('./admin/admin.component')
.then(m => m.AdminComponent),
},
];Standalone Directives and Pipes
typescript
@Directive({
selector: '[appHighlight]',
standalone: true,
})
export class HighlightDirective { /* ... */ }
@Pipe({
name: 'truncate',
standalone: true,
})
export class TruncatePipe implements PipeTransform { /* ... */ }Benefits
| Benefit | Description |
|---|---|
| No NgModule boilerplate | Components manage own dependencies |
| Better tree-shaking | Unused components are removed |
| Simpler lazy loading | loadComponent instead of loadChildren with module |
| Easier to learn | Less concepts for newcomers |
| Incremental adoption | Mix standalone + module-based |
Important:
Standalone components are the recommended approach for new Angular apps. They eliminate NgModule boilerplate, improve tree-shaking, and simplify lazy loading. Set standalone: true and import dependencies directly. Use bootstrapApplication() instead of platformBrowserDynamic().bootstrapModule().
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.