Services & RoutingCore· 40 min read

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.

Two routes: empty path for home, “about” for the about page
// 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.

The nav stays; the outlet swaps the page
<!-- 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>?

Answer: router-outlet marks the spot in the template where Angular renders whichever component matches the current URL.

✍️ Practice

  1. Add a contact route pointing to a ContactComponent.
  2. Add a routerLink for the new route in the nav and test switching pages.

🏠 Homework

  1. Build a two-page app (Home and About) with a nav bar, routerLink links and a single router-outlet.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →