Open In App

Standalone Components In Angular

Last Updated : 29 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Angular, standalone components are a new feature that allows you to create components without the need for a module. This can simplify your application structure and reduce boilerplate code.

This article will guide you through the concept of standalone components, including different approaches, and provide a step-by-step tutorial on how to implement them in your Angular application.

What is a Standalone Component?

Standalone components in Angular are components that can operate independently without requiring a module. This feature was introduced to streamline the development process and make Angular applications more modular and flexible. Standalone components are self-contained, meaning they include all the necessary dependencies and configurations within the component itself.

Prerequisites

Approach

Basic Standalone Component

import { Component } from '@angular/core';

@Component({
selector: 'app-basic-standalone',
templateUrl: './basic-standalone.component.html',
styleUrls: ['./basic-standalone.component.css'],
standalone: true
})
export class BasicStandaloneComponent {
// Component logic here
}

In this approach, the component is declared as standalone by setting the standalone property to true. This allows the component to be used independently without being part of a module.

Standalone Component with Dependencies

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
selector: 'app-standalone-with-deps',
templateUrl: './standalone-with-deps.component.html',
styleUrls: ['./standalone-with-deps.component.css'],
standalone: true,
imports: [CommonModule]
})
export class StandaloneWithDepsComponent {
// Component logic here
}

This approach demonstrates how to use standalone components with additional dependencies. By importing the CommonModule or other Angular modules directly within the component's metadata, you can still leverage Angular's built-in functionality while maintaining the component's standalone nature.

Migrating from NgModules to Standalone Components

To migrate from traditional NgModules to standalone components, you can start by refactoring existing components. Here's how:

  • Remove Component Declaration from Module: Remove the component from the declarations array in the corresponding NgModule.
  • Mark the Component as Standalone: Set the standalone property to true in the component's metadata.
  • Import Required Modules in Component: Add any necessary Angular modules directly in the component using the imports array.

Example:

Before (using NgModule):

@NgModule({
declarations: [OldComponent],
imports: [CommonModule],
})
export class OldModule { }

After (standalone component):

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
selector: 'app-standalone',
templateUrl: './standalone.component.html',
styleUrls: ['./standalone.component.css'],
standalone: true,
imports: [CommonModule],
})
export class StandaloneComponent { }

Standalone Component Integration

Standalone components can be integrated with existing Angular applications seamlessly. They can interact with other components, services, and Angular features as usual. Simply use them in templates or route configurations like any other component.

Example:

<app-standalone></app-standalone>

Integration with Router for Lazy-Loading Standalone Components

One of the powerful features of standalone components is their ability to be lazy-loaded with Angular's router. This is particularly useful for optimizing application performance.

Example of lazy-loading a standalone component:

import { Routes } from '@angular/router';

const routes: Routes = [
{
path: 'standalone',
loadComponent: () =>
import('./standalone/standalone.component').then((m) => m.StandaloneComponent),
},
];

This configuration ensures that the StandaloneComponent is loaded only when the user navigates to the /standalone route, reducing the initial load time.

Testing Standalone Components

Testing standalone components follows a similar approach to traditional Angular components. The primary difference is that you don't need to declare the component in a testing module.

Example of testing a standalone component:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { StandaloneComponent } from './standalone.component';

describe('StandaloneComponent', () => {
let component: StandaloneComponent;
let fixture: ComponentFixture<StandaloneComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [StandaloneComponent],
}).compileComponents();

fixture = TestBed.createComponent(StandaloneComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});

Steps to Create an Application

Step 1: Install Angular CLI

Ensure you have Angular CLI installed. If not, install it using:

npm install -g @angular/cli 

Step 2: Create a New Angular Project:

ng new standalone-demo
cd standalone-demo

Step 3: Generate Standalone Components:

ng generate component components/basic-standalone --standalone
ng generate component components/standalone-with-deps --standalone

Folder Structure

Screenshot-2024-08-16-001854
Folder Structure

Dependencies

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.12",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Example

We are importing both the components in app.component.ts to demonstrate both the approaches to demonstrate standalone components in Angular. Also, add selector of both the components in app.component.html fille.

HTML
<!--src/app/app.component.html--->
<app-basic-standalone></app-basic-standalone>
<app-standalone-with-deps></app-standalone-with-deps>
JavaScript

Output

standalone_component_output
Demonstration of Standalone Component in Angular



Similar Reads

three90RightbarBannerImg