Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 74 ยท Getting Started

NgModules and Legacy Angular Code

Read and migrate older Angular code. Learn what an NgModule is, how declarations, imports, exports and providers work, feature and shared modules, and how to move to standalone.

If you open an Angular project from before 2023, or a job's existing codebase, you will see files named app.module.ts and classes decorated with @NgModule. This tutorial teaches the modern style (standalone components), but a lot of real Angular code still uses modules, and you will have to read, fix and eventually migrate it.

This lesson is a field guide. You will learn what an NgModule does, the four arrays you will see in every one, the common module patterns, how to read module code, and how to migrate to standalone without a rewrite. It builds on How Angular Works and Your First Component.

Real versus stand-in. The typescript and bash blocks are real Angular code to read; the site cannot compile Angular. The runnable examples are stand-ins in TypeScript: one checks which template tags a module makes available (the error you would get from the compiler), and one converts a module's metadata into standalone imports lists.

The problem modules solved

A component's template uses other components, directives and pipes: <app-card>, *ngIf, | date. The compiler has to know what each name means. Before Angular 14, components could not say that themselves. Instead an NgModule declared a group of components and said what the group could use. Every component belonged to exactly one module, and the module was the compilation scope.

Standalone components moved that information to the component's own imports array. The idea is identical; only the place where you write it changed.

An NgModule in four arrays

TypeScript
// user.module.ts (the older style)
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';

import { UserListComponent } from './user-list.component';
import { UserCardComponent } from './user-card.component';
import { InitialsPipe } from './initials.pipe';
import { UserService } from './user.service';

@NgModule({
  declarations: [UserListComponent, UserCardComponent, InitialsPipe],
  imports: [CommonModule, ReactiveFormsModule],
  exports: [UserCardComponent],
  providers: [UserService],
})
export class UserModule {}
Array Meaning
declarations Components, directives and pipes that belong to this module. Each can be declared in exactly one module.
imports Other modules whose exported things this module's templates may use.
exports What this module makes available to modules that import it. Declared things are private unless exported.
providers Services registered in the injector, usually application-wide (Providers and Injection Tokens).

Two more fields appear less often: bootstrap (the root component, only in the root module) and schemas (silences "unknown element" errors, for example for custom elements).

The root module and bootstrapping

The root module imports BrowserModule, declares the root component and names it in bootstrap. A file called main.ts starts it:

TypeScript
// app.module.ts
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, AppRoutingModule, UserModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

// main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule);

The standalone equivalent is bootstrapApplication(App, appConfig) (Setup and the Angular CLI). Note HttpClientModule and RouterModule.forRoot(routes): they were the way to install HttpClient and the router, and today they are replaced by the provideHttpClient() and provideRouter() functions.

Common module patterns

Feature modules group everything for one area (users, orders, settings) behind one class. Routing modules hold RouterModule.forChild(routes) for a feature. Lazy loading loaded a whole module on demand:

TypeScript
const routes: Routes = [
  { path: 'users', loadChildren: () => import('./user/user.module').then((m) => m.UserModule) },
];

A shared module collected widely used pieces: it declared and exported buttons, cards and common modules so that feature modules could import one thing instead of ten. A core module held single-instance services and was imported once into the root module. forRoot() and forChild() are conventions for modules that configure providers once at the root and reuse declarations in features.

The modern equivalents are simpler: a route file for a feature (loadChildren: () => import('./users/users.routes'), see Nested and Lazy Routes), providedIn: 'root' services, and a plain TypeScript array for shared imports:

TypeScript
// shared.ts: replaces SharedModule
export const SHARED_IMPORTS = [DatePipe, Card, Button] as const;

@Component({ selector: 'app-page', imports: [SHARED_IMPORTS], template: `...` })
export class Page {}

The classic error

The compiler error you meet most with modules is that a tag or pipe is not known in the template. The three usual causes are: the component is not declared in any module, it is declared in a module but that module did not export it, or the consuming module did not import the module that exports it. Declared-but-not-exported is the one that surprises people, because the thing exists, yet its module keeps it private.

TypeScript A stand-in: which tags can a module's templates use?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the three results. AppModule can use the exported card but not the private list, and cannot use ngIf because it never imported CommonModule. OrdersModule gets ngIf and date through SharedModule's re-export, which is the whole point of a shared module. With standalone components the same checking happens per component, against its own imports.

Migrating to standalone

You do not need to rewrite an app to move away from modules. Standalone components and module-based ones can live together: a standalone component can import an NgModule (many libraries still export modules), and a module can import a standalone component.

The CLI has a migration that does the mechanical work in three passes:

Terminal
ng generate @angular/core:standalone

It asks which mode to run: convert all components, directives and pipes to standalone, then remove unnecessary NgModule classes, then bootstrap the application with the standalone API. Run one mode at a time, build and test, and commit between passes. Another schematic migrates *ngIf and *ngFor to @if and @for (Control Flow), and others convert @Input() to input() and constructors to inject().

A manual migration of one component looks like this:

TypeScript
// before
@Component({ selector: 'app-user-card', templateUrl: './user-card.component.html', standalone: false })
export class UserCardComponent {}
// declared in UserModule, which imports CommonModule

// after
@Component({ selector: 'app-user-card', templateUrl: './user-card.html', imports: [DatePipe] })
export class UserCard {}

The second stand-in imitates what the migration computes: for each declared component, it works out which imported modules' exports it actually uses, and writes the imports list.

TypeScript A stand-in: turn module metadata into standalone imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each component now lists only what it uses, and ReactiveFormsModule turns out to be unused in this module and can disappear. In the real migration, tooling plays this role and adds the right directives, pipes and modules.

Reading legacy code: a quick table

You see Modern equivalent
@NgModule({ declarations }) imports on each standalone component
bootstrapModule(AppModule) bootstrapApplication(App, appConfig)
HttpClientModule provideHttpClient()
RouterModule.forRoot(routes) provideRouter(routes)
BrowserAnimationsModule provideAnimationsAsync() or CSS animations (Animations)
*ngIf, *ngFor @if, @for (Control Flow)
loadChildren: () => import(...module) loadChildren returning a routes array, or loadComponent
constructor(private http: HttpClient) private http = inject(HttpClient)
@Input() name / @Output() done name = input() / done = output()

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the declarations array of an NgModule list?

    Declarations are the things the module owns. Each one can be declared in only one module. Services go in providers, other modules in imports.
  2. 2. A component is declared in FeatureModule, but AppModule's template gets "not a known element". What is the most likely cause?

    Declared things are private to their module. The module must export the component, and the consumer must import that module.
  3. 3. What replaces RouterModule.forRoot(routes) in a standalone app?

    provideRouter(routes) goes in the application config's providers and installs the router without a module.
  4. 4. Can a standalone component and module-based components exist in the same app?

    Standalone and modules interoperate, which is what makes gradual migration with the CLI schematic possible.

Summary

  • An NgModule groups components, directives and pipes (declarations), says what its templates can use (imports), what others may use (exports) and which services it registers (providers).
  • "Not a known element" in module code usually means a missing import or a missing export.
  • Shared, core, feature and routing modules have modern replacements: component imports, providedIn: 'root', route files and provide*() functions.
  • Migrate gradually with ng generate @angular/core:standalone, one pass at a time, building and testing between passes.

Next: learn what was added in each release, and what an upgrade involves, in What Changed in Each Angular Version.