Loading

Routing

  • Routing in Angular is the mechanism that enables navigation within a web application. 
  • It defines how different components and views are displayed based on the URL in the browser. 
  • In simpler terms, it's what allows you to switch between pages or views in your application without the need to reload the entire page.

Why Routing Matters 

Routing is vital for several reasons, and understanding its significance is crucial: 

  1. Enhanced User Experience: Routing allows users to navigate through different sections of your application seamlessly. It gives the feel of a traditional multi-page website while still being a single-page application.
  2.  Improved Organization: With routing, you can structure your application into multiple views or components, making it easier to manage and maintain. 
  3. Bookmarking and Sharing: Each route has a unique URL. This enables users to bookmark specific pages or share them with others, enhancing accessibility. 
  4. Lazy Loading: Angular's routing system supports lazy loading, which means that different parts of your application can be loaded on demand, improving initial load times.

Example: In the following example we will see how can we route our different components within the same application without reloading the whole page.

Step 1: Create an Angular project using Angular CLI.

ng new routing

Step 2: Create some new components i.e. user, about, home

ng g c user
ng g c about
ng g c home

Step 3: Now create the RouterLinks in the ‘app.component.html’ and also add the ‘<router-outlet></router-outlet> inside the HTML file.’

<h1>Routing Example</h1>
<div class="container">
  <a routerLink="">Home</a>
  <pre></pre>
  <a routerLink="about">About</a>
  <pre></pre>
  <a routerLink="user">User</a>
</div>
<router-outlet></router-outlet>

Step 4: Edit the 'app-routing.module.ts' to define the links and routings.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { UserComponent } from './user/user.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: 'about',
    component: AboutComponent
  },
  {
    path: 'user',
    component: UserComponent
  },
  {
    path: '',
    component: HomeComponent
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 5: Add CSS to ‘app.component.css’ for better styling.

h1 {
    text-align: center;
}

div {
    text-align: center;
}

Step 7: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200