We define a routes array to tell Angular which page or component to show when a user visits a specific URL. It helps users move around the app smoothly.
0
0
Defining routes array in Angular
Introduction
When you want to create a menu that links to different pages in your app.
When you want to show different components based on the URL in the browser.
When you want to protect some pages and only allow access if conditions are met.
When you want to add navigation with back and forward buttons working correctly.
When you want to organize your app into smaller parts that load only when needed.
Syntax
Angular
import { Routes } from '@angular/router'; export const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ];
The routes array is an array of objects.
Each object has a path and a component or other properties like redirectTo.
Examples
This route shows
HomeComponent when the URL is empty (root).Angular
export const routes: Routes = [ { path: '', component: HomeComponent } ];
This route uses a parameter
:id to show different profiles based on the URL.Angular
export const routes: Routes = [ { path: 'profile/:id', component: ProfileComponent } ];
This example redirects from
old-path to new-path.Angular
export const routes: Routes = [ { path: 'old-path', redirectTo: 'new-path', pathMatch: 'full' }, { path: 'new-path', component: NewComponent } ];
This wildcard route catches all unknown URLs and shows a Not Found page.
Angular
export const routes: Routes = [ { path: '**', component: NotFoundComponent } ];
Sample Program
This example defines four routes: 'home' and 'about' show their components, empty path redirects to 'home', and '**' catches unknown paths.
Angular
import { Component } from '@angular/core'; import { Routes } from '@angular/router'; @Component({ selector: 'app-home', template: '<h2>Home Page</h2>' }) export class HomeComponent {} @Component({ selector: 'app-about', template: '<h2>About Page</h2>' }) export class AboutComponent {} @Component({ selector: 'app-not-found', template: '<h2>Page Not Found</h2>' }) export class PageNotFoundComponent {} export const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ];
OutputSuccess
Important Notes
Routes are matched in order. The first match is used.
Use pathMatch: 'full' when redirecting from empty path to avoid partial matches.
Wildcard '**' should be last to catch all unmatched routes.
Summary
Routes array tells Angular which component to show for each URL path.
Each route has a path and a component or redirectTo.
Order matters: specific routes first, wildcard last.