All articles

Front-end8 min read

Angular Standalone Components: what they are, how to migrate

What standalone components are in Angular and how to migrate an NgModule project: the official schematic, routes with loadComponent, bootstrapApplication and inject().

Also in Português, Español, Français

If you've worked with Angular for a while, you know the ritual: you create a component, you need to declare it in an NgModule, import the module into another module, export it so someone else can use it... and when something doesn't show up on screen, the culprit is almost always a module you forgot to import.

Standalone components end that ritual. Each component says on its own what it needs, and NgModule is no longer required.

I first published this post on Medium in 2023, in Portuguese, and it became my most read post there. This is the revised version: the code left the screenshots and became text you can copy, I fixed two mistakes that were in the original, and I updated what changed in Angular since then.

The migration examples come from angular-shop, Loiane Groner's demo project showing what's new in Angular.

TL;DR#

  • A standalone component is a component that declares its own dependencies in the imports of @Component, with no NgModule needed.
  • Since Angular 19 it's the default: every new component is born standalone. For an old component to keep depending on a module, it needs standalone: false.
  • The migration is automatic, in three steps: ng generate @angular/core:standalone, run three times, once for each mode, building in between.
  • Routes you migrate by hand: each *-routing.module.ts becomes an exported Routes array, loaded with loadChildren or, if it's a single component, with loadComponent.
  • bootstrapApplication replaces AppModule, and providers become functions: provideRouter, provideHttpClient.
  • inject() doesn't depend on standalone. It works in any class created by dependency injection and has its own schematic for the migration.

What a standalone component is#

Before, a component only existed inside a module. The module was the one saying what the component could use:

// before: the module declares the component and imports what it needs
@NgModule({
  declarations: [CartComponent],
  imports: [CommonModule, RouterModule],
})
export class CartModule {}

A standalone component carries that list inside itself:

// after: the component imports its own dependencies
@Component({
  selector: 'app-cart',
  imports: [CurrencyPipe, RouterLink],
  templateUrl: './cart.component.html',
})
export class CartComponent {}

Notice there's no standalone: true. Up to Angular 18 you had to write that line. Starting with Angular 19, standalone is the default, and it's the component that still depends on a module that has to say so, with standalone: false.

With NgModule, the module decides what the component sees. Standalone, the component decides on its own

In practice, this changes three things:

  1. It's clear what the component depends on. Open the file and the list is right there, not scattered across modules.
  2. Lazy loading gets finer. You can load a single component on a route, without creating a module just for that.
  3. Fewer files to maintain. cart.module.ts goes away, cart-routing.module.ts goes away.

And you don't need to migrate everything at once: standalone components and modules live side by side in the same project. A standalone component can be imported into an NgModule, and a module can go into the imports of a standalone component.

Migrating with the official schematic#

Angular has a schematic that does most of the work. Before running it, the official guide asks for three things:

  • the project is on Angular 15.2 or newer;
  • the project builds without errors;
  • you're on a clean Git branch, with everything committed. That way, if the migration makes a mess, a git restore . undoes it.

There's just one command:

ng generate @angular/core:standalone

It asks which mode to run. Run all three, in this order, building and testing the app between each one:

  1. "Convert all components, directives and pipes to standalone": turns each component, directive and pipe into standalone and fills the imports of each one with what it uses.
  2. "Remove unnecessary NgModule classes": deletes the modules that ended up empty. Whatever it can't delete on its own, it marks with a TODO(standalone-migration) comment for you to sort out.
  3. "Bootstrap the application using standalone APIs": swaps the bootstrapModule(AppModule) in main.ts for bootstrapApplication.
The same command, three times, one mode at a time. Build between each one

In a large project, you can go in parts with the --path option, migrating one folder at a time:

ng generate @angular/core:standalone --path src/app/cart

After the three steps, the guide itself suggests a cleanup:

  • look for the leftover NgModule classes and delete what you can by hand;
  • run the unit tests and fix what broke;
  • run the formatter and the linter, because the generated code doesn't always follow the project's style.

Converting the routes#

After the schematic, feature modules (like CartModule and ProductsModule) often still exist, just to load the routes. The standalone schematic doesn't do that part, so it's on you. The good news: it's the simplest part.

The routing module becomes an array#

Before, each feature had a module just to register its routes:

// cart-routing.module.ts (before)
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'
import { CartComponent } from './cart/cart.component'
 
const routes: Routes = [{ path: '', component: CartComponent }]
 
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class CartRoutingModule {}

After, it's just the array, exported:

// cart.routes.ts (after)
import { Routes } from '@angular/router'
import { CartComponent } from './cart/cart.component'
 
export const CART_ROUTES: Routes = [{ path: '', component: CartComponent }]

Same for products:

// products.routes.ts (after)
import { Routes } from '@angular/router'
import { ProductFormComponent } from './product-form/product-form.component'
import { ProductsListComponent } from './products-list/products-list.component'
 
export const PRODUCTS_ROUTES: Routes = [
  { path: '', component: ProductsListComponent },
  { path: 'new', component: ProductFormComponent },
]

In the first version of this post, products.routes.ts exported CART_ROUTES (I copied it from the cart file and forgot to change it), while the main routes imported a different name. The way it was, the code didn't even compile. Here there's only one name: PRODUCTS_ROUTES.

The main routes point to the arrays#

In app-routing.module.ts, loadChildren loaded a module:

// app-routing.module.ts (before)
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'products' },
  {
    path: 'products',
    loadChildren: () => import('./products/products.module').then((m) => m.ProductsModule),
  },
  {
    path: 'cart',
    loadChildren: () => import('./cart/cart.module').then((m) => m.CartModule),
  },
]
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Now it loads the routes array. Lazy loading works the same: the products code is only downloaded when someone goes to /products.

// app.routes.ts (after)
import { Routes } from '@angular/router'
 
export const APP_ROUTES: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'products' },
  {
    path: 'products',
    loadChildren: () => import('./products/products.routes').then((m) => m.PRODUCTS_ROUTES),
  },
  {
    path: 'cart',
    loadChildren: () => import('./cart/cart.routes').then((m) => m.CART_ROUTES),
  },
]

One route, one component: loadComponent#

The cart has a single route. It doesn't need a routes file: with loadComponent, the route loads the component directly, and cart.routes.ts can be deleted.

// app.routes.ts
{
  path: 'cart',
  loadComponent: () => import('./cart/cart/cart.component').then((m) => m.CartComponent),
}

And if the file uses export default, you don't even need the .then:

// cart.component.ts: export default class CartComponent {}
{
  path: 'cart',
  loadComponent: () => import('./cart/cart/cart.component'),
}

loadChildren accepts the same shortcut when the routes file has export default.

Do you have routes loading components directly, without lazy loading, and want to change them all at once? There's another schematic for that: ng generate @angular/core:route-lazy-loading swaps component for loadComponent in the routes it finds.

main.ts without AppModule#

The schematic's third step already switches the bootstrap to bootstrapApplication. But if the project had an AppRoutingModule, it usually ends up in importProvidersFrom, still as a module:

// main.ts (before)
bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(BrowserModule, AppRoutingModule),
    provideHttpClient(withInterceptorsFromDi()),
  ],
})

Replace the routing module with provideRouter, passing the array:

// main.ts (after)
import { bootstrapApplication } from '@angular/platform-browser'
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
import { provideRouter } from '@angular/router'
import { AppComponent } from './app/app.component'
import { APP_ROUTES } from './app/app.routes'
 
bootstrapApplication(AppComponent, {
  providers: [provideRouter(APP_ROUTES), provideHttpClient(withInterceptorsFromDi())],
})

BrowserModule can go too: bootstrapApplication already brings what it did. With that, you can safely delete:

  • app-routing.module.ts, cart-routing.module.ts and products-routing.module.ts;
  • cart.module.ts and products.module.ts, if the schematic hasn't deleted them yet.

The inject() function#

In the original I presented inject() as a "new option with standalone components". It has nothing to do with standalone. Since Angular 14, inject() works in any class that dependency injection creates (component, directive, pipe, service), with or without a module. It only showed up alongside because the two arrived around the same time.

What it does: it fetches a dependency from the active injector, without needing the constructor.

// constructor injection
export class ProductsListComponent {
  constructor(
    private service: ProductsService,
    private cartService: CartService,
  ) {}
}
 
// with inject()
export class ProductsListComponent {
  private service = inject(ProductsService)
  private cartService = inject(CartService)
}

Why prefer it? The code gets shorter, the types get more precise (according to the docs themselves, it also works better with standard JavaScript decorators), and it also works in functions, like a functional route guard. The only rule is to call inject() in an injection context: in the constructor, in a class field initializer or in a function Angular calls in that context (like guards and resolvers). In a setTimeout or a click handler, it throws an error.

And there's a schematic to convert everything:

ng generate @angular/core:inject

Conclusion#

Standalone components make each component responsible for its own dependencies, and that makes the project easier to read, to split and to load bit by bit. With the schematic, the boring part of the migration is automatic. What's left for you is the routes and main.ts, and that's not much.

If your project is still full of NgModule, the path is: clean branch, the schematic's three modes with a build between them, routes by hand, and then ng generate @angular/core:inject to wrap it up.

References#

  • Front-end
  • angular
  • standalone
  • typescript
  • migration
  • lazy loading

Written by

Software engineer and designer. I write about what I run into while building apps, APIs and products.