Core Concepts

Routing

Set up Angular Router to navigate between views and build multi-page applications.

Angular Router

The Angular Router enables navigation between different components (views) based on the current URL.

Route Configuration

Define routes as an array of objects mapping URL paths to components.

Router Directives

  • routerLink — navigate to a route (replaces href)
  • routerLinkActive — add CSS class when route is active
  • <router-outlet> — where matched components are rendered

Route Guards

Protect routes with guards:

  • CanActivate — prevent unauthorized access
  • CanDeactivate — prevent leaving with unsaved changes

Example

typescript
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { UsersComponent } from './users/users.component';
import { UserDetailComponent } from './users/user-detail.component';
import { authGuard } from './guards/auth.guard';

export const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: 'users',
    component: UsersComponent,
    canActivate: [authGuard],
    children: [
      { path: ':id', component: UserDetailComponent },
    ]
  },
  // Lazy loading
  {
    path: 'admin',
    loadComponent: () =>
      import('./admin/admin.component').then(m => m.AdminComponent),
    canActivate: [authGuard],
  },
  { path: '**', redirectTo: '' }, // Wildcard
];

// Navigation in template
// <a routerLink="/users" routerLinkActive="active">Users</a>
// <a [routerLink]="['/users', user.id]">{{ user.name }}</a>

// Programmatic navigation
import { Router, ActivatedRoute } from '@angular/router';

export class UserDetailComponent implements OnInit {
  userId!: number;

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.userId = +this.route.snapshot.paramMap.get('id')!;
  }

  goBack() {
    this.router.navigate(['/users']);
  }
}
Try it yourself — TYPESCRIPT