Angular - Router Reference



This angular chapter will "highlight" (cover) the core or important routing concepts starting from the basic as follows:

Router Imports

In Angular, the Router is an optional feature or a service that represents a particular component (section) view for the given URL. For example, the URL localhost:4200/dashboard will represent the DashboardComponent.

However it is not a part of the Angular core, but it has its own library package;@angualr/router. In case to use it as another angular package you need to import it as follows:

import { provideRouter } from '@angular/router';

Also, add it in the "providers array" as well located in the app.config.ts file:

providers: [provideRouter(routes)]

Configuration

An Angular application with routing has a single instance of the Router service. When the browser URL changes, the router searches for a matching Route to determine the component to display.

A router has no routes until we configure it, which means we must define the paths. The following example defines five different routes, and configures them via the provideRouter method, and adds the routes to the routes array in the app.routes.ts file:

import { Routes, UrlSegment } from '@angular/router';
import { ViewComponent } from './view/view.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ProfileComponent } from './profile/profile.component';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';

export const routes: Routes = [
    {path: 'dashboard', component: DashboardComponent},
    {path: 'view/:id', component: ViewComponent},
    {
        path: 'profile', component: ProfileComponent, 
        data: {title: 'User Profile'}},
    {path: '', redirectTo: '/dashboard', pathMatch: 'full'},
    {path: "**", component: PagenotfoundComponent}
];

The above routes array contains multiple routes for the application to navigate through various components when the user interacts. Let's explain them one by one:

  • In the above routes array, each Route maps a URL path to a component. There are no leading slashes in the path.
  • The :id in the second route is a token for the route parameter. This is used whenever you want to view specific details (such as user or customer details). For example, in the URL localhost:4200/user/view/10, the value of the id parameter is 10.
  • The data property in the third route is a place to store arbitrary data associated with this specific route. It is used to store items such as "titles", "static" "data", etc.
  • The empty path (path: ' ') in the fourth route represents the default path for the application. It is the "place to go" when the path in the URL is empty at the start. It redirects to the /dashboard and later navigates to the Dashboard component.
  • In the last route, path: "**" (known as a wildcard route), it redirects to PageNotFound when an incorrect URL is entered in the browser, such as localhost:4200/wrongurl. It should always be defined at the end of the routes.

Router Outlet

In Angular, the RouterOutlet is a directive that belongs to the router library, but it is used as a component. It is commonly placed in the root component (app.component.html) to make a "spot or a location" where the router should display the loaded component.

If the router-outlet is not used, the routing will not work until you use the selector (e.g., selector: 'app-dashboard') of a component in the root component.

This means that without the router-outlet, you need to directly place the "component's selector" in the root component to ensure it is displayed.

<router-outlet></router-outlet>

When the browser URL for an application requests /dashboard, this path will match the router path "/dashboard" and display the DashboardComponent as a "sibling" element of the RouterOutlet.

To navigate users from one component to another, Angular uses the routerLinkdirective, which is used to set the path for a specific route. This directive binds a URL path to a clickable element, like a button or a link, allowing navigation within your Angular application.

<h3>Angular RouterLink</h3>
<nav>
  <a routerLink="/home">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

The routerLink directive in the anchor (<a>) element gives control over that element.

The RouterLinkActive is a directive that toggles (adds or removes) CSS classes for the active RouterLink based on the current RouterState or when the link is active.

You may see the property binding on each anchor tag to the RouterLinkActive as follows:

<a routerLink = "" routerLinkActive="...">Link</a>

The expression to the right of the equal sign (=) contains a space-delimited string of CSS classes. The Router adds these classes when the link is "active" and removes them when the link is "inactive".

You set the RouterLinkActive directive to a string of classes such as routerLinkActive = "active myLink" (where myLink is a CSS class) or bind it to a component property that returns such a string, as shown below:

routerLinkActive="componentStringProperty"

Router State

The RouterState is a class that represents the current state of the router. It's part of the Angular Router module and provides information about the current route, including the activated routes.

After each successful navigation lifecycle, the router builds the tree ofActivatedRouteobjects that make the current state of the router. You can access the currentRouterStatefrom anywhere in the application using the"Routerservice" and its"properties".

In addition, each ActivatedRoute in the RouterState provides methods to traverse up and down the route tree to get information from "parent", "child", and "sibling" routes.

Activated Route

The route path and parameters are available through an injected router service called ActivatedRoute. Using this service, you can read the URL parameter data. For example, given the URL http://localhost:4200/user/view/userId?=se32sd, you can retrieve the user ID as follows:

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-view',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './view.component.html',
  styleUrl: './view.component.css'
})
export class ViewComponent implements OnInit{
  constructor(private route: ActivatedRoute){}
  userId: any;
  ngOnInit(): void {
    this.route.params.subscribe(response =>{
      this.userId = response['id'];
      console.log(this.userId);
    });
  }
}

Following is a list of important properties of the ActivatedRoute

Property Descriptions
url An Observable of the route paths is an array of strings, each representing a part of the route path.
data AnObservablethat contains thedataobject provided for the route.
params AnObservablethat contains the required and optional parameters specific to the route.
paramMap AnObservablethat contains amapof the required and optional parameters specific to the route.
queryParamMap AnObservablethat contains amapof the query parameters available to all routes.
queryParams AnObservablethat contains the query parameters available to all routes.

Router Events

While navigating, theRouteremits navigation events through theRouter.eventsproperty. Below is a list of important router events and their descriptions:

Router Event Descriptions
NavigationStart This event is triggered when navigation starts.
RoutesRecognized Triggered when the Router parses the URL and the routes are recognized.
GuardsCheckStart It is triggered when the Router begins the guards phase of routing.
GuardsCheckEnd It triggered, when the Router finishes the Guards phase of routing successfully.
ResolveStart It is triggered when the Router begins the resolve phase of routing.
ResolveEnd Triggered when the Router finishes the resolve phase of routing successfully.
NavigationEnd This event is triggered when navigation ends successfully.
NavigationCancel It is triggered when navigation is canceled.
NavigationError Triggered when navigation fails due to an unexpected error.

Router Terminology

Following is a list of a few router terms and their meanings:

Router part (term) Descriptions
Router The router manages the navigation from one component to the other and displays the application component for active URL.
provideRouter A function provides the necessary service providers for navigating through the application view.
RouterModule A module provides necessary services and directives for managing application navigation and routing.
Routes It defines an array of route configuration objects that define the navigation paths and their corresponding components.
Route It defines how the router should navigate to a component based on a URL pattern.
RouterOutlet A directive (<router-outlet>) that spots places where the router displays a view (or loaded components).
RouterLink A directive used for binding a clickable HTML element (links, buttons, etc.) to a route.
RouterLinkActive A directive used for toggling (adding or removing) classes from an HTML element when an associatedrouterLinkcontained on or inside the element becomes active or inactive.
ActivatedRoute A service provided to each route component that contains route-specific information such as route parameters (e.g., path = "view/:id"), static data, resolve data, etc.
RouterState An object that represents the current state of the router, containing information about the active routes and their hierarchy.

Multiple Choice Questions (MCQ's):

Here we have mentioned a few MCQs to test your knowledge on the current concept:

Answer : B

Explanation:

The RouterModule needs to be imported to configure the router in an Angular application

Q 2 − What directive is used to apply a CSS class to the current active route in Angular?

A − [routerLink]

B − [routerLinkActive]

C − [routerActiveClass]

D − [routerClass]

Answer : B

Explanation:

In Angular, the [routerLinkActive] directive is used to add a CSS class to an element when its associated router link is active.

Q 3 − In Angular, what value should you set to [routerLinkActiveOptions] to make sure the class is applied only when the exact URL is matched?

A − { exact: true }

B − { precise: true }

C − { strict: true }

D − { match: true }

Answer : A

Explanation:

In Angular, by setting [routerLinkActiveOptions]="{ exact: true }", you ensure that the routerLinkActive class is applied only when the current link is active (matching full URL).

Answer : A

Explanation:

To retrieve a route parameter in Angular, use this.route.paramMap.get('id') within the ActivatedRoute service.

Answer : C

Explanation:

The router-outlet can be placed in any component template where you want to render the routed components.

Advertisements