Angular 19 introduces Standalone Components, a powerful way to build modular applications without the need for NgModules. This approach simplifies development, reduces boilerplate, and improves performance. In this guide, we'll walk through creating and using standalone components effectively.
Set up a new Angular project:
ng new angular-standalone-app --standalone
cd angular-standalone-app
Ensure Angular 19 is installed:
ng version
Standalone components are self-contained and can be used without being part of an NgModule.
Example of creating a standalone component:
ng generate component components/Header --standalone
Create a Standalone Header Component
import { Component } from '@angular/core';
@Component({
selector: 'app-header',
standalone: true,
template: `<h1>Welcome to Angular 19</h1>`,
})
export class HeaderComponent {}
Use Standalone Component in the App
main.ts
:import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent);
Use the component inside app.component.ts
:
import { Component } from '@angular/core';
import { HeaderComponent } from './components/header.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [HeaderComponent],
template: `<app-header></app-header><p>Main content goes here...</p>`,
})
export class AppComponent {}
Import External Modules as Needed
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [CommonModule],
template: `<p>Dashboard works!</p>`,
})
export class DashboardComponent {}
Use Routing with Standalone Components
provideRouter()
:import { provideRouter, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: DashboardComponent },
];
bootstrapApplication(AppComponent, { providers: [provideRouter(routes)] });
Standalone components in Angular 19 make applications more modular, scalable, and maintainable. By removing NgModules, developers can simplify application architecture, improve performance, and make components easier to manage. 🚀