Standalone components let you create Angular components without needing a module. This makes your code simpler and easier to manage.
0
0
Standalone component declaration in Angular
Introduction
When you want to build a small, reusable UI piece quickly.
When you want to avoid creating extra Angular modules for simple components.
When you want to improve app startup time by reducing module overhead.
When you want to use Angular's new recommended way to build components.
When you want to share components easily across different parts of your app.
Syntax
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-example', standalone: true, template: `<p>Hello from standalone component!</p>`, imports: [] // optional: other standalone components or directives }) export class ExampleComponent {}
The key part is standalone: true inside the @Component decorator.
You can add other standalone components or directives in the imports array if needed.
Examples
A basic standalone component with a simple template.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-simple', standalone: true, template: `<h1>Simple Standalone</h1>` }) export class SimpleComponent {}
This standalone component imports
CommonModule to use Angular features like event binding.Angular
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-with-common', standalone: true, imports: [CommonModule], template: `<button (click)="count = count + 1">Clicked {{count}} times</button>` }) export class WithCommonComponent { count = 0; }
Sample Program
This standalone component shows a counter. It uses Angular signals to track the count and updates the display when the button is clicked.
Angular
import { Component, signal } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-counter', standalone: true, imports: [CommonModule], template: ` <h2>Counter</h2> <button (click)="increment()">Increment</button> <p>Count: {{ count() }}</p> ` }) export class CounterComponent { count = signal(0); increment() { this.count.set(this.count() + 1); } }
OutputSuccess
Important Notes
Standalone components do not need to be declared in any NgModule.
You can use imports to bring in other standalone components or Angular modules.
Standalone components help reduce boilerplate and improve app modularity.
Summary
Standalone components simplify Angular by removing the need for NgModules.
Use standalone: true in the component decorator to declare them.
They can import other standalone components or modules via the imports array.