Life without NgModules

Standalone components were a preview in Angular 14 and became stable in 15. With 15. 2 there's now a migration that converts an existing app for you.

Standalone components were a preview in Angular 14 and became stable in 15. With 15.2 there’s now a migration that converts an existing app for you. So it’s a good time to look at what changes when NgModules go away, and what they were quietly doing for you.

A component imports what it uses

With NgModules, a component could use anything its module (or a shared module) imported. Now each component lists its own dependencies:

@Component({
  selector: 'app-orders',
  standalone: true,
  imports: [NgIf, NgFor, AsyncPipe, DatePipe, RouterLink],
  template: `
    <ul *ngIf="orders$ | async as orders">
      <li *ngFor="let order of orders">
        <a [routerLink]="['/orders', order.id]">{{ order.createdAt | date }}</a>
      </li>
    </ul>
  `,
})
export class OrdersComponent {
  orders$ = inject(OrdersService).orders$;
}

It’s more typing, but you can open one file and see exactly what the template depends on. You can import CommonModule if you’d rather not list NgIf, NgFor and friends one by one.

The classic mistake is forgetting one of these. If NgIf is missing, there’s no compile error. The list just doesn’t render. Angular 15.2 at least warns you:

warning NG8103: The *ngIf directive was used in the template, but neither the NgIf directive nor the CommonModule was imported.

If you miss your old SharedModule, an array works too. Angular flattens nested arrays in imports:

export const SHARED_IMPORTS = [NgIf, NgFor, AsyncPipe, DatePipe, RouterLink] as const;

@Component({
  standalone: true,
  imports: [SHARED_IMPORTS],
  // ...
})

Bootstrapping without AppModule

main.ts gets shorter, and the providers move there:

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes),
    provideHttpClient(withInterceptors([authInterceptor])),
    importProvidersFrom(SomeLibraryModule),
  ],
});

provideRouter and provideHttpClient are new in 15 and replace RouterModule.forRoot() and HttpClientModule. Interceptors can now be plain functions:

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  return next(
    token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req,
  );
};

Not every library has caught up yet. If one only ships a module with a forRoot(), wrap it in importProvidersFrom and it works fine.

Lazy loading

You can lazy load a single component, or a list of routes, with no module in between:

export const routes: Routes = [
  { path: '', component: OrdersComponent },
  {
    path: 'reports',
    loadComponent: () =>
      import('./reports/reports.component').then((m) => m.ReportsComponent),
  },
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
  },
];

Where services live now

This is the part NgModules used to hide. Anything with providedIn: ‘root’ works exactly as before. The question is what to do with services that a lazy module used to provide.

Routes can have their own providers:

{
  path: 'reports',
  providers: [ReportsStore],
  loadComponent: () =>
    import('./reports/reports.component').then((m) => m.ReportsComponent),
}

ReportsStore is available to the reports route and its children, and nowhere else. One thing to know: that injector is created the first time the route activates, and it isn’t destroyed when you navigate away. So the store keeps its state between visits, same as a service in a lazy NgModule did. If you need a fresh instance on every visit, provide it in the component’s providers instead.

Migrating an existing app

Angular 15.2 has a schematic for it:

ng generate @angular/core:standalone

It runs in three steps, and you pick one each time you run it: convert components, directives and pipes to standalone, remove NgModules that are no longer needed, and switch to bootstrapApplication. Run them in that order, and build and test between steps. The first step does most of the work. The second may leave a few modules it isn’t sure about, which you can clean up by hand.

You don’t have to go all in, either. Standalone components can be declared next to module-based ones, imported into NgModules, and the other way around. New features can be standalone today while the rest of the app moves over bit by bit.