Back to course

Defining Basic Routes

The Complete Angular Developer: From Zero to Hero

32. Defining Basic Routes

Routes are defined in the Routes array using objects that map a path (the URL segment) to a component.

Route Configuration Structure

Each route object requires:

  • path: A string representing the URL segment.
  • component: The component class that Angular should display when the path matches.

typescript import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [ // 1. Default Route (Path is empty string) -> '/' { path: '', component: HomeComponent },

// 2. Specific path -> '/about' { path: 'about', component: AboutComponent },

// 3. Wildcard Route (Must be last!) -> Catch-all for 404 { path: '**', component: NotFoundComponent } ];

Understanding the Wildcard Route (**)

The wildcard path (**) matches any URL that hasn't been matched by earlier routes. It is crucial to define this route last in the array, as the router processes routes sequentially.

Path Matching Strategy

By default, Angular uses a 'prefix' matching strategy, meaning it looks for the path at the start of the URL. However, for most routes, we usually want exact matches, especially for the root path.

We explicitly define the path match strategy for the root route using pathMatch: 'full':

typescript const routes: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full' }, // Requires exact match on '/' // ... other routes ];