Routing In Angular

|
| By Webner

Introduction to Angular

Angular is a front-end framework that is used for building client-side web applications for the mobile and desktop web and Routing is one of the important features for any front-end framework.

Angular Router

It enables developers to build a Single Page Application for organizing an application into multiple views and allow navigation between these views. It is installed from a @angular/router package and provides a complete routing library.

After creating a project import router module from ‘@angular/router’ in-app-routing.module.ts

import { Routes, RouterModule } from ‘@angular/router’;

Routes

A route is an object (instance) that gives information about which component is a map to a specific path.

{ path: ‘New/path/’, component: ComponentName}

Here, path specifies the path of the route and component specifies which component is mapped to the route.

Route Matching Strategies

  • A path can be empty which usually refers to the main URL of the application and can take prefix (default) or full
  • By default, a path-matching strategy is Prefix, where it checks URL elements from the left, stops when there is a match.
    For example:
    ‘/user/101/detail’ → matches the user/:id
  • If the path-match strategy is ‘full’ it will match the entire URL and is important to do when redirecting to an empty-path because the empty path is the prefix for any URL, it will create an endless loop.{ path: ‘Users’, pathMatch: ‘full’, component: UserComponent}

Navigation Directives

Angular Router provides two navigation directives :

RouterLink: It is used for creating a link and replaces the “href” attribute in tag.
<a [routerLink]=”/user”>Products</a>

RouterLinkActive: It is used for marking the active link in which class will be added for active link
<a routerLink=”/user” routerLinkActive=”active-class”>Bob</a>
//here active-class is the class which is removed when URL changes

Leave a Reply

Your email address will not be published. Required fields are marked *