Routing (Pages)
Routing shows different components for different addresses, like / for home and /cart for the cart, without reloading the page.
Angular apps are single-page applications (SPAs): the browser loads the app once, and then Angular swaps components as you move between "pages". The address bar still changes (/cart, /product/42), so links can be shared and the back button works, but navigation feels instant because the whole page isn't reloaded.
Routes can include parameters (product/:id) to show one item, and can be lazy loaded - the code for a page downloads only when a visitor first opens it, which keeps the app fast to start.
1. List the routes
Example
// app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home';
import { Cart } from './cart';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'cart', component: Cart },
];2. Turn routing on
Example
// 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)],
};3. Show the page and add links
Example
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="/cart">Cart</a>
</nav>
<router-outlet />
`,
})
export class App {}<router-outlet /> is the place where the current page appears. A new app made with ng new already has routing set up.Key points
- Routes map addresses to components.
provideRouter(routes)turns routing on.<router-outlet />shows the current page;routerLinkmakes links.
📝 Test yourself
1. What does routing do?
2. Where does the current page appear?
3. Fill in the attribute for a link to another page:
<a ="/cart">Cart</a>
