Jali's Pancake Stall's page now has a menu list and an order summary, but it's all piled onto one screen. Customers want the menu on one page and their order on another. Each page also needs its own address that they can share.
That's the router's job. The router gives one Angular app several pages, each with its own address (/menu, /orders). Moving from one page to another happens without reloading the page: the browser doesn't ask the server for a new page. Picture Jali's Pancake Stall with a Menu room and an Orders room. The receptionist holds a list of "this address, that room". The contents of any room are served at the same single table. Moving through an inside door is quick, and you keep what you're carrying. Leaving through the front door and coming back in means everything starts over. In Angular, the receptionist's list is the routes (the route list), the table is <router-outlet>, the inside door is routerLink, and the front door is a plain <a href>. What you carry is what the services hold, such as the cart.
The route list: addresses to components
The route list is written in app.routes.ts, then set up in app.config.ts:
// src/app/app.routes.ts
import { Routes } from '@angular/router'
import { MenuPage } from './menu/menu'
import { OrdersPage } from './orders/orders'
import { NotFound } from './not-found/not-found'
export const routes: Routes = [
{ path: '', redirectTo: 'menu', pathMatch: 'full' },
{ path: 'menu', component: MenuPage },
{ path: 'orders', component: OrdersPage },
{ path: '**', component: NotFound },
]
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core'
import { provideHttpClient } from '@angular/common/http'
import { provideRouter } from '@angular/router'
import { routes } from './app.routes'
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()],
}
| Address | What shows |
|---|---|
/ |
redirected to /menu, so MenuPage |
/menu |
MenuPage |
/orders |
OrdersPage |
/promo |
NotFound |
- Each route pairs a
path(the address, with no leading slash) with acomponent(the component shown at that address). The list's type isRoutes, from@angular/router. provideRouter(routes)sets up the router with that list, next toprovideHttpClient()from the HTTP Client lesson. (Since Angular 21, theprovideHttpClient()line is only needed to add interceptors or other options. In Angular 20 and older, it is required.)- The router reads the list from the top, and the first route that matches is the one used.
router-outlet: where the page appears
App's template holds the heading, the navigation links in <nav>, and a place for the page:
// src/app/app.ts
import { Component } from '@angular/core'
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router'
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterLink, RouterLinkActive, RouterOutlet],
template: `
<h1>Jali's Pancake Stall</h1>
<nav>
<a routerLink="/menu" routerLinkActive="active">Menu</a>
<a routerLink="/orders" routerLinkActive="active">Orders</a>
</nav>
<router-outlet />
`,
})
export class App {}
<router-outlet />is where Angular places the matching route's component. The heading and<nav>stay in place; only the contents of<router-outlet />change. When you move from/menuto/orders, Angular removes MenuPage and creates OrdersPage.routerLink="/orders"makes the link move to that address without reloading the page.routerLinkActive="active"adds the classactiveto the link whose address is open. For a link to/, add[routerLinkActiveOptions]="{ exact: true }". Without it, the link to/counts as active on every page, because every address starts with/.RouterLink,RouterLinkActiveandRouterOutletmust all be inimports. WithoutRouterLink, the link has nohrefand clicking it does nothing. WithoutRouterOutlet, the console writesNG0304: 'router-outlet' is not a known element.
The first exercise uses the same shape: a <nav> holding <a routerLink="/">Home</a> and <a routerLink="/about">About</a>, then <router-outlet />. In the second exercise, you write the list: export const routes: Routes = [...] with '' to HomeComponent, 'about' to AboutComponent, and '**' to NotFoundComponent.
routerLink vs href
Say the cart from the Services and DI lesson already holds 2 pancakes, and you move to the Orders page:
routerLink="/orders" |
<a href="/orders"> |
|
|---|---|---|
| The page | isn't reloaded | is reloaded from the server |
| The app's JavaScript | keeps running | is downloaded and run again from zero |
CartService |
the same instance, contents kept | created again, empty |
| The Orders page shows | Items in cart: 2 | Items in cart: 0 |
href makes the browser leave the app and ask the server for the app again. Every service is created again, so the cart is empty: the Orders page shows 0 items. Use routerLink for pages inside the app, and href for addresses outside it (Jali's Instagram, a PDF of the menu).
The empty route, pathMatch, and the wildcard
{ path: '', redirectTo: 'menu', pathMatch: 'full' }redirects an address that is completely empty to/menu.pathMatch: 'full'means the whole address must match, not only its start. WithoutpathMatch, Angular 18 in development mode (ng serve) refuses the whole list as soon as the router is created. The app stops halfway: only the heading before<nav>shows, and the console writesNG04014: Invalid configuration of route '{path: "", redirectTo: "menu"}': please provide 'pathMatch'. The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.'**'(the wildcard, meaning "anything") matches any address, so put it at the bottom. If it's first in the list, that route catches/menuand/orderstoo, and every page shows NotFound.- Without
'**', an address missing from the list makes the navigation (the move to another page) fail: the page doesn't move, and the console writesNG04002: Cannot match any routes. URL Segment: 'promo'. path: '/menu'(with a slash) is refused too:NG04014: Invalid configuration of route '/menu': path cannot start with a slash.
Moving pages from code
Sometimes the page has to move without a click, for example to /orders after an order is sent. Ask for Router with inject(), then call navigate:
private router = inject(Router)
sendOrder() {
this.router.navigate(['/orders'])
}
navigate(['/orders']) and navigateByUrl('/orders') both move without reloading, like routerLink. navigate takes an array of address parts, while navigateByUrl takes the whole address as text.
⚠️ Links that reload, routes that don't match
hreffor your own pages. The app reloads and everything in its services is lost. UserouterLink.- Forgetting
imports.RouterLink,RouterLinkActiveandRouterOutletmust be in theimportsof the component that uses them. '**'not last, or an empty route withredirectTobut nopathMatch: 'full'.- Exercise detail. The first exercise has no route list yet, so clicking its links in the editor makes the console write
NG04002: Cannot match any routes. That's expected and isn't graded. What's graded: a<nav>, at least 2<a>inside it withrouterLink, and<router-outlet />. In the second exercise, write each route exactly as{ path: '', component: HomeComponent }(path then component, with a comma), and give the list the type: Routes. The three components are already in the starter (the exercise's starting code), with anAppComponentholding three links and<router-outlet />. Export the list. The grader then opens/, clicksAbout, clicksBroken link(/missing), and reads the<h2>that shows.
TL;DR: The router gives one Angular app several pages, each with its own address. A route list of type Routes pairs addresses with components ({ path: 'menu', component: MenuPage }), and it is set up with provideRouter(routes). The matching route's component appears in <router-outlet />. routerLink="/orders" moves without reloading, so what services hold, like the cart, stays. <a href> reloads the whole app, and everything starts from zero. routerLinkActive marks the link whose address is open. A route for the empty address ('') that redirects with redirectTo needs pathMatch: 'full'. '**', which matches any address, goes at the bottom for a 404 page (a "not found" page). router.navigate(['/orders']) moves pages from code.
⚡ The route list: addresses to components
Write:
export const routes: Routes = [
{ path: '', redirectTo: 'menu', pathMatch: 'full' },
{ path: 'menu', component: MenuPage },
{ path: 'orders', component: OrdersPage },
{ path: '**', component: NotFound },
]
Meaning: The router gives an Angular app several pages and moves between them without reloading. This route list pairs addresses (path) with the component that shows. The router reads the list from the top, and the first route that matches is the one used. The empty address is redirected to menu. pathMatch: 'full' means the whole address must match, not only its start. '**' matches any address, so it goes at the bottom. The list is set up with provideRouter(routes).
In the second exercise, write each route exactly as { path: '', component: HomeComponent }, path first then component, and give the list the type : Routes.
⚡ router-outlet: where the page appears
Write:
<nav>
<a routerLink="/menu" routerLinkActive="active">Menu</a>
<a routerLink="/orders" routerLinkActive="active">Orders</a>
</nav>
<router-outlet />
Meaning: The matching route's component is placed in <router-outlet />, while the <nav> stays in place. routerLink makes a link move to its address without reloading the page. routerLinkActive adds the class active to the link whose address is open.
⚡ routerLink moves without a page reload
Write:
<a routerLink="/orders">Orders</a>
<a href="/orders">Orders</a>
Guess first: the cart (the service that holds the order) already holds 2 pancakes. You move to the Orders page through <a href>. How many items are in the cart?
None. href makes the browser load the whole app again from the server, so every service is created from zero. Through routerLink, the page isn't reloaded and the cart still holds 2.
Meaning: Use routerLink for pages inside the app, and href for addresses outside it.