Horje
A Complete Guide To Angular Routing

Angular Routing is a technology to build single-page applications that provide multi-page services at a single port. It enables seamless navigation and loading of the different pages. When an Angular app is started then the whole component is only loaded at once and dynamically reloads the requested pages through routing technology.

WhatsApp-Image-2024-07-02-at-52016-PM

Angular Routing

This tutorial is going to give you a complete guide to How Angular Routing actually works and what are the features and their advantages. At the end of this tutorial you will be able to implement routing feature in your Angular Project and also you will have a clear idea about how angular routing makes an application very efficient by loading only those component instead of whole pages which has requested by an user.

Introduction to Angular Routing

The Angular router is a core part of the Angular application and is responsible for mapping URLs to components and rendering different components based on the current URL matches in an Angular application.

  • We should have clear idea about this Routing feature, it is responsible for page rendering not for navigating links. Many times developers have misconception that when we click navigation bar then page will change but the scenario is different whenever we interact with any navigation elements then it only set the URL or we can say change the URL.
  • After changing the URL, the responsible Angular Routing Module notes down the new URL and then renders components accordingly.

Prerequisites

Steps to Create an Angular Application

Step 1: After the global setup of Node Js and npm Packages now we have to install Angular globally by using the below mentioned command

npm install -g @angular/cli

Step 2: Run the command below to create a new Angular Application.

ng new project_name

Step 3: Change the directory using below command to enter in our Project environment.

cd project_Name

Step 4: Run the command below to create components.

ng generate component Home
ng generate component About
ng generate component Contact

Step 5: Run the below command to start the server.

ng serve

Dependencies

"dependencies": {
    "@angular/animations": "^18.1.0",
    "@angular/common": "^18.1.0",
    "@angular/compiler": "^18.1.0",
    "@angular/core": "^18.1.0",
    "@angular/forms": "^18.1.0",
    "@angular/platform-browser": "^18.1.0",
    "@angular/platform-browser-dynamic": "^18.1.0",
    "@angular/platform-server": "^18.1.0",
    "@angular/router": "^18.1.0",
    "@angular/ssr": "^18.1.0",
    "express": "^4.18.2",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.3"
}

Folder Structure

Screenshot-2024-04-22-055152

Folder Structure

HTML
<!-- app.component.html -->

<h1>Angular Router App</h1>
<nav>
    <ul>
        <li><a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">
          Home</a></li>
        <li><a routerLink="/about" routerLinkActive="active" ariaCurrentWhenActive="page">
          About</a></li>
        <li><a routerLink="/contact" routerLinkActive="active" ariaCurrentWhenActive="page">
          Contact</a></li>
    </ul>
</nav>
<router-outlet></router-outlet>
HTML
<!-- home.component.html -->
    
    <p>Home Component</p>
HTML
<!-- about.component.html -->
    
    <p>About Component</p>
HTML
<!-- contact.component.html -->
    
    <p>Contact Component</p>
JavaScript
// app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

export const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent }
];
JavaScript
//app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { RouterLink, RouterLinkActive } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, RouterLink, RouterLinkActive],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    title = 'route';
}


Example :- Step to run the application: Open the terminal and type the following command –

  1. The file app.component.html includes the main page where rendering process start and ends .
  2. The file app.routes.ts is basically for enlisting all the Route related components.
  3. The file home.component.html simply includes home component elements.
  4. The file about.component.html simply includes About component elements.
  5. The file contact.component.html simply includes Contact component elements.
ng serve

Output :


We can see :

  • Home component at : http://localhost:4200/
  • About component at : http://localhost:4200/about
  • Contact Component at : http://localhost:4200/contact

Some Important Angular routing concepts

1. Child Routes

Child routes in Angular are used to create nested routes within a parent route. This is useful for organizing routes that share a common path or component structure. You might have a main component with several sub-components, each accessible via its own route. It can be implemented like –

const routes: Routes = [
    {
        path: 'parent',
        component: ParentComponent,
        children: [
            {
                path: 'child1',
                component: Child1Component
            },
            {
                path: 'child2',
                component: Child2Component
            }
        ]
    }
];

2. Lazy Loading

Lazy loading is a technique used to load feature modules on demand rather than upfront. This improves the performance of your application by loading only the necessary parts initially and loading additional parts as needed.

To implement lazy loading, you define a route with the ‘loadChildren‘ property instead of ‘component’. This property points to a function that returns the module to be loaded.

const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];

3. Route Guards

Route guards are used to control access to certain routes based on conditions such as authentication status, user roles, or other criteria.

Angular provides several types of route guards –

  • CanActivate: Determines if a route can be activated.
  • CanDeactivate: Determines if a route can be exited.
  • CanActivateChild: Determines if child routes can be activated.
  • CanLoad: Determines if a module can be loaded.


Here is the some Functions and Module explanation which are used in above code snippet :-

  • RouterOutlet : Directive to specify where the router should render the active component.
  • RouterLink : Directive to create links to other routes.
  • RouterLinkActive : Directive to highlight the active link in your navigation bar.
  • ActivatedRoute : Service to access information about the current route, such as the route parameters.
  • NavigationExtras : Object to pass additional data to the router when navigating to a new route.

Finally, we well-versed through Angular Routing and now you are able to implement Routing in your Angular Project.

Angular Routing FAQ’s –

What is Angular routing, and why is it important?

Angular Routing is a technology to build single-page-application which provides multi-page-services at single port. it is very important to to create Single Page Applications (SPAs) with multiple views, and managing navigation between them .

What are the core building blocks of Angular routing?

Here is some core blocks which are responsible for Angular Routing – a. RouterModule b. Routes Configuration c. RouterOutlet d. RouterLink e. Router Service f. Route Guards g. Lazy Loading h. Child Routes

What are the key benefits of using Angular Routing?

Declarative Configuration: Routes are defined in a clear, structured way. Built-in Guards and Resolvers: Provides more control over navigation. Seamless Integration: Works natively within Angular’s ecosystem.

How does Angular Routing differ from React Routing?

Angular Routing, typically uses a more declarative approach with the RouterModule and route configuration within Angular modules. React Routing, on the other hand, uses react-router which is a library that allows for more flexibility but requires more manual setup in component files.

Which should I choose for my project: Angular Routing or React Routing?

The choice depends on the project requirements and the development team’s familiarity with the frameworks. Angular Routing is a great choice for those using Angular due to its integration and built-in features, while React Routing offers flexibility and a component-based approach suitable for React applications.




Reffered: https://www.geeksforgeeks.org


AngularJS

Related
Folder Structure of Angular Project Folder Structure of Angular Project
Building Template-Driven Form in Angular Building Template-Driven Form in Angular
Testing With The Angular HttpClientTestingModule Testing With The Angular HttpClientTestingModule
How To Implement CanDeactivateFn in Angular15? How To Implement CanDeactivateFn in Angular15?
How To Consuming JSON APIs in AngularJS Application? How To Consuming JSON APIs in AngularJS Application?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18