Angular - Standalone Component
Source: Dev.to
Overview
Angular standalone components enable you to build components without an NgModule, simplifying application structure and improving modularity. Introduced in Angular v14, this feature reduces boilerplate and allows for more flexible code organization.
Key Characteristics
- Self‑contained unit – A standalone component can operate independently without being declared inside an
NgModule. - Marked with
standalone: true– Set this flag on a component, directive, or pipe to make it standalone. - Direct imports – Instead of relying on NgModules, you import other components, directives, and pipes directly via the
importsarray. - Incremental adoption – Existing projects can gradually migrate to the standalone style without breaking changes.
- Lazy loading – Standalone components can be lazy‑loaded easily.
Example
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-hello',
standalone: true,
imports: [CommonModule],
template: `
## Hello Standalone!
`
})
export class HelloComponent {}
- The
standalone: trueflag makes the component independent. - The
importsarray directly brings inCommonModule(or any other standalone components). - No
NgModuleis required; you can bootstrap this component directly inmain.ts.
Benefits
- Simplified structure – Reduces reliance on NgModules.
- Flexibility – Components are easier to reuse across different parts of an application.
- Cleaner codebase – Less boilerplate, more focus on functionality.
- Gradual migration – Existing apps can adopt standalone components step by step.
- Lazy loading – Straightforward to implement for performance optimization.
Resources
- GitHub repository (source code & examples)
- LinkedIn profile (author)