Sub topic 2
Routes as configuration: a quick refresher
Lazy loading changes how a route's code is delivered, but the route table itself stays the same. This chapter reviews what that table is and how the router reads it. The later chapters then change one line at a time.
This chapter assumes you can write a standalone component and have bootstrapped an Angular app with the CLI. It also assumes you know what import and export do in TypeScript. You don't need to have used lazy loading yet.
A route table is data
The Angular router doesn't discover pages by scanning folders. You give it an array of plain objects typed as Routes. Each object is a Route, and each one says: "when the URL looks like this, show that." The router reads the array, matches the current URL against it, and renders the result.
Because the table is ordinary data, you can build it, split it across files, and export it like any other value. Lazy loading depends on this. A feature area can ship its own Routes array, and the router can fetch that array later.
Here is a small but complete route table for an online shop.
// src/app/app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductListComponent } from './products/product-list.component';
import { ProductDetailComponent } from './products/product-detail.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', component: HomeComponent, title: 'Home' },
{ path: 'products', component: ProductListComponent, title: 'Products' },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: 'shop', redirectTo: 'products', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent, title: 'Not found' },
];Each entry uses a few properties that matter later:
pathis a URL segment pattern, written without a leading slash.''means the empty path.:idis a route parameter.**is a wildcard that matches anything.componentis the class to render when the route matches.redirectTosends the router to another path instead of rendering anything.titlesets the document title after a successful navigation.
Registering the table and rendering it
A route table does nothing until you register it with provideRouter and place a <router-outlet> somewhere in a template.
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};// src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, RouterLink],
template: `
<nav>
<a routerLink="/">Home</a>
<a routerLink="/products">Products</a>
</nav>
<router-outlet />
`,
})
export class AppComponent {}// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));provideRouter(routes) is the single place where the router receives its configuration. In the preloading chapter you'll pass extra feature functions there, such as withPreloading(...). The route table itself is the first argument and doesn't change.
The <router-outlet> is a placeholder. When a route matches, Angular creates the route's component and inserts it next to the outlet.
How the router matches a URL
The router walks the array from top to bottom and uses the first entry that matches. Order is therefore part of the configuration. This is the most common source of "why is my page not showing" errors in a route table.
Several rules follow from this:
- Put specific routes before general ones. A wildcard
**entry matches everything, so it must be last. Anything after it is unreachable. - A route with
redirectTorenders nothing itself. The router restarts matching with the new URL. - If no entry matches and there is no wildcard, navigation fails with an error such as
Cannot match any routes.
Prefix and full matching
By default, a route's path is matched as a prefix of the remaining URL. That is fine for most routes, but it surprises people with the empty path.
The empty string is a prefix of every URL. If you write the next entry, every URL redirects to home, and you get a redirect loop or an unexpected page.
// Wrong: '' is a prefix of every URL
{ path: '', redirectTo: 'home' }Set pathMatch: 'full' so the entry matches only when the whole remaining URL is empty.
{ path: '', redirectTo: 'home', pathMatch: 'full' }The shop example above uses pathMatch: 'full' on the shop redirect for a similar reason. With the default prefix matching, /shop/anything would also be caught.
| `pathMatch` | Matches when | Typical use |
|---|---|---|
| `'prefix'` (default) | The route path is the start of the remaining URL | Normal routes, and routes with `children` |
| `'full'` | The route path equals the entire remaining URL | Redirects from `''` |
Route parameters
A segment starting with a colon captures part of the URL. In products/:id, the URL /products/42 produces the parameter id with the value '42'. The value is always a string, so convert it yourself if you need a number.
You can read parameters through ActivatedRoute. A simpler option, available when you enable it, is to bind them to component inputs with withComponentInputBinding().
// app.config.ts (updated)
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding())],
};// src/app/products/product-detail.component.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h1>Product {{ id() }}</h1>`,
})
export class ProductDetailComponent {
// Filled from the :id segment of the URL
id = input.required<string>();
}The input name has to match the parameter name. You will need this later, because lazy routes use the same parameter rules as eager ones.
Nesting routes with children
A route can have a children array. The child routes are matched against whatever remains of the URL after the parent's path. The parent component renders first, and the matching child renders in the parent's own <router-outlet>.
// Nested version of the products routes
import { Routes } from '@angular/router';
import { ProductShellComponent } from './products/product-shell.component';
import { ProductListComponent } from './products/product-list.component';
import { ProductDetailComponent } from './products/product-detail.component';
export const routes: Routes = [
{
path: 'products',
component: ProductShellComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: ':id', component: ProductDetailComponent },
],
},
];// src/app/products/product-shell.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-product-shell',
standalone: true,
imports: [RouterOutlet],
template: `
<h2>Catalog</h2>
<router-outlet />
`,
})
export class ProductShellComponent {}With this table:
/productsrenders the shell with the list inside it./products/42renders the shell with the detail view inside it.
Child routes don't repeat the parent's path. The URL is built by joining the segments.
A route can also have no component at all and only children. This kind of component-less route is a grouping container. It lets several children share a guard, a data value, or a providers array without adding a wrapper component. Lazy loading makes heavy use of this pattern.
Other route properties you will meet
The router reads many more properties than the ones above. You don't need all of them now, but you should recognize them, because later chapters use them on lazy routes.
| Property | What it does | Where it shows up in this tutorial |
|---|---|---|
| `loadComponent` | Fetches a standalone component on demand | Lazy loading a single component |
| `loadChildren` | Fetches a child `Routes` array on demand | Lazy loading a feature area |
| `providers` | Creates route-level services for this route and its children | Providing services for a lazy route tree |
| `data` | Attaches static values to a route | Selective preloading |
| `canMatch` | Decides whether the route can match at all | Keeping unauthorized users from downloading a chunk |
| `canActivate` | Decides whether an already-matched route can be entered | Compared with `canMatch` |
Two of these look alike and are easy to confuse. canActivate runs after the route matched. canMatch runs during matching, and if it returns false, the router acts as if the route did not exist and keeps looking at later entries. That difference decides whether a lazy chunk is downloaded, so keep it in mind.
Why this matters for lazy loading
Look again at the first route table. Its top lines are static imports:
import { HomeComponent } from './home/home.component';
import { ProductListComponent } from './products/product-list.component';A static import is resolved at build time. The bundler follows it, includes the imported file in the same output, and everything that file imports in turn. So every component named in a component: property is in the main bundle, whether the user ever visits that route or not. In a large app with fifty routes, the first page then downloads the code for all fifty.
The route table is only a description. The component property holds a class that the file already imported. To defer a feature, you remove the static import and describe the route differently. Instead of holding the class, the route holds a function that will fetch it later. That is the whole idea behind loadComponent and loadChildren, which the next chapters cover.
Two details of the table carry over unchanged:
- The router still matches on
path. A lazy route has a path like any other, so matching, ordering,pathMatch, and parameters work as described above. - The router has to decide which route matches before it can fetch anything. So the
pathof a lazy route must stay in the main bundle, and only the code behind it moves out.
Common mistakes in a route table
These errors are cheap to avoid, and they show up often in code reviews.
- A wildcard placed too early.
{ path: '**', ... }in the middle of the array hides every route after it. Keep it last. - A redirect from
''withoutpathMatch: 'full'. This causes a redirect loop or sends every URL to the target. - A leading slash in
path. Write'products', not'/products'. The router rejects paths that start with a slash. - Treating parameters as numbers.
:idyields the string'42'. Comparing it with===against a number never matches. - Specific routes after parameterized ones. If
products/:idcomes beforeproducts/new, the URL/products/newmatches the first entry withid = 'new'. Putproducts/newfirst.
Exercise
A teammate wrote this route table. The URL /products/new shows the product detail page with the text "Product new" instead of the new-product form, and a request for an unknown URL like /xyz shows a blank page. Name the two problems and give the corrected array. export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products/:id', component: ProductDetailComponent }, { path: 'products/new', component: ProductFormComponent }, { path: '**', component: NotFoundComponent }, { path: 'about', component: AboutComponent }, ];
Show answer
First, products/:id comes before products/new, so /products/new matches the parameterized route with id = 'new'. Second, the wildcard is not last, so it matches everything after it, which makes about unreachable. Move the specific routes above the parameterized one and put the wildcard last: export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'products/new', component: ProductFormComponent }, { path: 'products/:id', component: ProductDetailComponent }, { path: '', component: NotFoundComponent }, ];
Exercise
Why does every class named in a component: property end up in the main bundle, even if the user never visits that route?
Show answer
The class is brought into the route file with a static import statement. The bundler resolves static imports at build time and includes the imported file, and everything it imports, in the same output. The router never has to ask for the code later, so the bundler has no reason to split it into a separate chunk.