Setting Up Routing
Angular's router maps URLs to components, enabling single-page application navigation without page reloads.
Enabling the Router
// 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)],
};
Defining Routes
// app.routes.ts
import { Routes } from '@angular/router';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products', component: ProductsComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: '**', component: NotFoundComponent },
];
Router Outlet
The <router-outlet> directive marks where the router renders the matched component:
@Component({
selector: 'app-root',
imports: [RouterOutlet],
template: `
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/products">Products</a>
</nav>
<router-outlet></router-outlet>
`,
})
export class AppComponent {}
Route Path Patterns
| Pattern | Matches | Example URL |
|---|---|---|
'' |
Root (empty path) | / |
'about' |
Exact match | /about |
'products/:id' |
Parameter | /products/123 |
'**' |
Wildcard (any URL) | /anything/else |
Wildcard Route (404)
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: '**', component: NotFoundComponent },
];
The wildcard route must be last. It catches all unmatched URLs.
Quiz
1. What directive marks where the router renders the matched component?
2. What does routerLink do?
3. Where should the wildcard route (**) be placed?
Flashcards
Question
How do you enable routing in Angular?
Click to reveal answer
Answer
provideRouter(routes) in app.config.ts providers array.
Question
What does routerLink do?
Click to reveal answer
Answer
Builds hrefs handled by the Angular router without page reload.
Question
Where does the wildcard route go?
Click to reveal answer
Answer
Last in the routes array. Catches all unmatched URLs.
Revision Notes
Key Takeaways
- 1. provideRouter(routes) enables routing in app.config.ts
- 2. <router-outlet> renders the matched component
- 3. routerLink enables SPA navigation without page reload
- 4. Wildcard route (**) must be last for 404 handling
Interview Tips
- • Explain how the router matches URLs to components
- • Be ready to describe routerLink vs programmatic navigation
- • Mention routerLinkActive for styling active links
Cheat Sheet
Route Configuration Cheat Sheet
Enable router:
provideRouter(routes) // in app.config.ts
Define routes:
{ path: 'products/:id', component: ProductDetailComponent }
{ path: '**', component: NotFoundComponent } // must be last
Template:
<a routerLink="/products">Products</a>
<a [routerLink]="['/products', id]">Detail</a>
<router-outlet></router-outlet>