In Angular, routing lets you move between different components or views inside a single-page application (SPA) without reloading the whole page. The Angular Router allows you to:
<router-outlet>.path to a component.'' is usually mapped to a default or home component.A basic routing setup in Angular involves three main steps:
app-routing.module.ts).Routes.routerLink and <router-outlet> in the template to navigate and display components.
// app-routing.module.ts (basic routing setup)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // default route for home page
{ path: 'about', component: AboutComponent } // navigates to AboutComponent
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In your root component template (usually app.component.html), you add navigation links using routerLink and a <router-outlet> where components will be displayed.
<!-- app.component.html (navigation with router links) -->
<nav>
<a routerLink="">Home</a> |
<a routerLink="about">About</a>
</nav>
<router-outlet></router-outlet>
RouterModule.forRoot(routes) configures the Angular Router with the routes you defined.routerLink="about", the URL changes to /about without reloading the page.AboutComponent into the <router-outlet>.''), HomeComponent is displayed as the default route.This is how Angular achieves fast, smooth navigation while still behaving like a single-page application.
AppRoutingModule into your AppModule to activate routing.routerLinkActive to highlight the currently active navigation link.'about', 'contact', not 'cmp1').
<!-- Adding routerLinkActive to highlight active route -->
<nav>
<a routerLink="" routerLinkActive="active-link" [routerLinkActiveOptions]="{ exact: true }">Home</a> |
<a routerLink="about" routerLinkActive="active-link">About</a>
</nav>
ContactComponent and add a route for it (e.g., 'contact').Contact using routerLink and highlight it using routerLinkActive.AboutModule.Router events to understand navigation flow.
// Adding a new Contact route in app-routing.module.ts
import { ContactComponent } from './contact/contact.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent } // new contact route
];