Back to Angular Course

Angular Course

What is Routing in Angular?

Routing in Angular facilitates navigation between different views within a Single Page Application (SPA) without reloading the page. It leverages browser history to simulate the user experience of a Multi-Page Application while remaining a single page.

Configuring Routes

In Angular 17, route configuration has been refined. Routes are now defined in a separate file, typically named app.routes.ts, which is a departure from the previous convention where routes were often defined within the AppModule or a dedicated AppRoutingModule. This change promotes a clearer separation of concerns and improves modularity.

app-routing.module.ts

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { HomeComponent } from './components/home/home.component'; import { CreateEmployeeFormComponent } from './components/create-employee-form/create-employee-form.component'; import { ContactUsComponent } from './components/contact-us/contact-us.component'; const routes: Routes = [ { path: 'dashboard', component: DashboardComponent }, { path: '', component: HomeComponent }, { path: 'create-employee', component: CreateEmployeeFormComponent }, { path: 'contact-us', component: ContactUsComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

Router Outlet

<router-outlet> acts as a dynamic placeholder in the App component, rendering the component of the current route. When a route is activated, Angular loads the corresponding component into the <router-outlet> element.

app.component.html

<app-navbar/> <router-outlet></router-outlet> <app-footer />

Navigation Navigation can be achieved in two ways:

  • Declaratively: Using the routerLink directive in HTML templates. navbar.component.html
<nav class="navbar navbar-expand-md navbar-dark bg-dark flex-column"> <a class="navbar-brand" href="#">Employee Management System</a> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#home" routerLink="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#dashboard" routerLink="/dashboard">Dashboard</a> </li> <li class="nav-item"> <a class="nav-link" href="#create" routerLink="/create-employee">New Hire</a> </li> <li class="nav-item"> <a class="nav-link" href="#contactus" routerLink="/contact-us">Contact Us</a> </li> </ul> </div> </nav> <br />
  • Programmatically: Through the Router service in TypeScript.
navigateToDashBoard() { this.router.navigate(['/dashboard']); }