A standalone component is an advanced Angular component, and it does not belong to any NgModule. It is stable and launched in the Angular 16+ version.
No @NgModule required in Standalone Components.
Syntax:
@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule],
template: `<h2>Home Component</h2>`
})
export class HomeComponent {}
Note: In a standalone component, it should be standalone: true
What are the benefits of Standalone components?
There are many benefits of Standalone components.
1. It is used to reduce code complexity.
2. It is used to improve tree-shaking and performance.
3. It is used to make components more self-contained.
How to create a Standalone Component?
You can create an Angular component using the command below.
Syntax:
ng generate component componentName --standalone
OR
ng g c componentName --standalone
Example:
ng generate component componentName --user
Example of Standalone Component
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-user',
standalone: true,
imports: [CommonModule],
template: `
<h3>User Profile</h3>
<p>Standalone component example</p>
`
})
export class UserComponent {}
Importing Other Directives in a Standalone Component
You can import other Directives and Modules into your standalone component.
imports: [
CommonModule,
RouterModule,
FormsModule
]
Importing Other Standalone Components into Your Standalone Component
You can import other Standalone components into your standalone component.
imports: [HeaderComponent, FooterComponent]
Standalone Components vs NgModules
| Standalone Components | NgModules |
|---|---|
| It has Minimal Boilerplate. | It has More Boilerplate. |
| It is very Easy to learn. | It is not easy to learn. |
| It is very simple to create Lazy loading. | It is very complex to create Lazy loading. |
| Making apps easier to scale. | Making apps are not easier to scale. |
Angular Standalone Components – Interview Questions
Q 1: What are Standalone Components?
Ans: Standalone components are Angular components that do not require NgModules. They can directly import dependencies.
Q 2: Why were standalone components introduced?
Ans: They simplify application structure and reduce boilerplate code.
Q 3: How do you create a standalone component?
Ans: By setting standalone: true in the component decorator.
Q 4: Can standalone components use Angular directives?
Ans: Yes, they import required directives and modules directly in the imports array.
Q 5: Are standalone components suitable for large applications?
Ans: Yes, they improve modularity and reduce complexity.