Routing & router-outlet
Routes map URLs to components, and router-outlet is the spot where the matching component appears.
What you will learn
- Define routes that map paths to components
- Place a router-outlet for pages to render
- Link between pages with routerLink
Many “pages” in one app
A single-page app does not load new pages from a server, but it can still feel like it has pages: Home, About, Tasks. The Router swaps which component is shown based on the URL — instantly, with no full reload.
Define your routes
A route is a small object linking a URL path to a component. You list them in an array.
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
export const routes: Routes = [
{ path: '', component: HomeComponent }, // the home page
{ path: 'about', component: AboutComponent }
];Note: Output:
(No visible output — this just defines the map.)
Visiting / will show HomeComponent; visiting /about will show AboutComponent. Next we tell Angular where to render them.
Where pages appear: router-outlet
Put a <router-outlet> tag in your shell template. Angular renders the matching component right there, while the rest of the page (like a nav bar) stays put.
<!-- app.component.html -->
<nav>
<a routerLink="">Home</a>
<a routerLink="about">About</a>
</nav>
<router-outlet></router-outlet>Note: Output:
Home About
[the current page’s content appears here]
Clicking “About” changes the URL to /about and swaps the outlet content to the About page — with no reload. The nav above the outlet never disappears.
Watch out: Use routerLink for in-app navigation, not a normal href. A plain href reloads the whole app from the server, throwing away the smooth single-page feel.
Tip: When you ran ng new and answered “Yes” to routing, the CLI already created the routes file and added <router-outlet> for you. You mostly just add new routes to the array.
Q. What is the job of <router-outlet>?
✍️ Practice
- Add a
contactroute pointing to aContactComponent. - Add a
routerLinkfor the new route in the nav and test switching pages.
🏠 Homework
- Build a two-page app (Home and About) with a nav bar,
routerLinklinks and a singlerouter-outlet.