Sub topic 7
The route configuration file
This chapter covers src/app/app.routes.ts, the file that maps URLs to components. It assumes you have read the bootstrapping chapter, so you know that app.config.ts registers the router with provideRouter(routes). It also assumes you know TypeScript arrow functions and basic standalone components.
Where the file fits
ng new creates app.routes.ts next to app.config.ts. Depending on your CLI version, ng new may ask whether to add routing, or it may always generate the file. The file's job is small: it exports an array named routes. The array is passed to provideRouter, and provideRouter is listed in the providers of the application config.
import { Routes } from '@angular/router';
export const routes: Routes = [];An empty array is valid. With no routes, every URL matches nothing, and the router renders nothing. The array is plain data, so you can read it top to bottom to see every page the application can show.
The router only draws a matched component where the root template contains a <router-outlet>. If you add routes and see a blank page, a missing outlet is the first thing to check.
import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink],
template: `
<nav>
<a routerLink="/">Home</a>
<a routerLink="/products">Products</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet />
`,
})
export class AppComponent {}Because the component is standalone, RouterOutlet and RouterLink must appear in its imports array. Forgetting this produces a compile error about an unknown element or an unrecognized routerLink binding.
Anatomy of a route
Each entry in the array is a Route object. The properties you will use most often are:
| Property | Purpose |
|---|---|
| `path` | The URL segment to match, without a leading slash. `''` matches the empty path. |
| `component` | A component that is imported eagerly and bundled with the main code. |
| `loadComponent` | A function returning a dynamic `import()`. The component is fetched on first visit. |
| `loadChildren` | A function that lazily loads another `Routes` array. |
| `children` | A nested `Routes` array, rendered in an outlet inside the parent component. |
| `redirectTo` | Sends the navigation to another path. |
| `pathMatch` | Either `'prefix'` (the default) or `'full'`. It controls how much of the URL must match. |
| `title` | Sets the document title when the route is active. |
Here is a complete file that uses most of them:
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent, title: 'Home' },
{
path: 'about',
title: 'About us',
loadComponent: () =>
import('./about/about.component').then((m) => m.AboutComponent),
},
{
path: 'products',
loadChildren: () =>
import('./products/products.routes').then((m) => m.PRODUCT_ROUTES),
},
{ path: 'home', redirectTo: '', pathMatch: 'full' },
{ path: '**', redirectTo: '' },
];The home route is imported with a normal import statement, so it ships in the initial bundle. The about and products routes use dynamic import(). The build tool splits each into a separate chunk that the browser downloads only when the user first navigates there. Routes the user is likely to visit first usually stay eager. Routes behind a login or deep in the application are good lazy candidates.
How matching works
The router checks routes from the first array element to the last. The first route that matches wins, and later routes are never examined. Order therefore matters.
Three consequences follow from this model:
- The wildcard route
{ path: '**' }matches any URL, so it must be last. Placed earlier, it hides every route below it. - Specific paths come before parameterized ones.
products/newmust be listed beforeproducts/:id, ornewwill be captured as an id. pathvalues never start with/. Writingpath: '/about'throws an error at startup.
Why `pathMatch: 'full'` matters
The default pathMatch is 'prefix'. The router consumes as much of the URL as the route's path covers, and the rest goes to child routes. An empty path is a prefix of every URL. So this route redirects everything:
{ path: '', redirectTo: 'home' }Angular rejects it at configuration time, because a redirect with an empty path needs pathMatch: 'full'. With 'full', the whole remaining URL must equal the path, so only the exact root URL is redirected:
{ path: '', redirectTo: 'home', pathMatch: 'full' }Parameters and child routes
A segment starting with a colon is a route parameter. path: ':id' matches one segment, and the router stores its value under the name id. The component reads it through an input if you enable withComponentInputBinding(), or through ActivatedRoute.
For a feature with several pages, put its routes in their own file next to the feature code:
import { Routes } from '@angular/router';
import { ProductListComponent } from './product-list/product-list.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
export const PRODUCT_ROUTES: Routes = [
{ path: '', component: ProductListComponent, title: 'Products' },
{ path: ':id', component: ProductDetailComponent },
];When the parent route in app.routes.ts uses loadChildren, these paths are relative to products. So /products shows the list and /products/42 shows the detail page with id equal to 42. This keeps app.routes.ts short as the application grows, and each feature folder owns its own URLs. The folder organization chapter builds on this idea.
You can create the components for this feature with the generator:
ng generate component products/product-list
ng generate component products/product-detailThe generator does not edit app.routes.ts or the feature routes file. You always register the route yourself.
Router features added in the application config
Extra router behavior is switched on by passing feature functions to provideRouter, not by editing routes:
import { ApplicationConfig } from '@angular/core';
import {
provideRouter,
withComponentInputBinding,
withInMemoryScrolling,
} from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withInMemoryScrolling({ scrollPositionRestoration: 'enabled' }),
),
],
};withComponentInputBinding() lets a component declare id = input<string>() and receive the :id value directly. withInMemoryScrolling restores scroll position on back navigation.
Common errors
- Blank page, no error. The root template has no
<router-outlet />, orRouterOutletis missing from the root component'simports. NG04002: Cannot match any routes. The URL matches no route and there is no wildcard. Add a'**'route as the last entry, or fix the path.- Wrong page for a valid URL. An earlier route, often a wildcard or a
:paramroute, is matching first. Reorder the array. - Redirect loop or "Invalid configuration" for an empty path. A
redirectToonpath: ''lackspathMatch: 'full'. - Lazy
.then()returns undefined. The name inside.then((m) => m.AboutComponent)does not match the exported class. Check the export, or use a default export andimport('./about/about.component')withloadComponent, which accepts default exports. - Deep links return 404 in production. The route works inside the application but fails on a page refresh. The web server must serve
index.htmlfor unknown paths, because the browser's request never reaches the router otherwise.ng servehandles this for you, but a static host often does not.
Exercise
A route list contains, in this order: { path: '**', redirectTo: '' }, { path: 'about', component: AboutComponent }. A user opens /about. What do they see, and how do you fix it?
Show answer
They are redirected to the home route, because the router uses the first matching route and '**' matches every URL. Move the wildcard route to the end of the array, after about.
Exercise
You write { path: '', redirectTo: 'home' } and Angular reports a configuration error. What is missing, and what does it change?
Show answer
pathMatch: 'full' is missing. With the default 'prefix', an empty path would match every URL. With 'full', the redirect applies only when the entire remaining URL is empty, so only the root URL redirects.
Exercise
You generate a component with ng generate component products/product-list, but visiting /products shows nothing. Which two things must you check?
Show answer
First, a route for products (or a loadChildren entry pointing at a feature routes file) must exist in the routes array, because the generator does not add routes. Second, the root component must have <router-outlet /> in its template and RouterOutlet in its imports.