retrieve the name or path of the route currently being accessed

Here is the navigation bar code snippet:

 <nav class="menu">
   <a routerLink="textArea" class="menu-item">text-area</a>
   <a routerLink="dropdown" class="menu-item">dropdown</a>
   <a routerLink="autosuggest" class="menu-item">autosuggest</a>
   <a routerLink="manageCookies" class="menu-item">manage-cookies</a>
   <a routerLink="progressBar" class="menu-item">progress-bar</a>
 </nav>
 <router-outlet></router-outlet>

The routes declared in the app.routing are as follows:

 const routes: Routes = [
   {
     path: 'textArea',
     component: TextAreaComponent,
   },
   {
     path: 'dropdown',
     component: DropdownComponent,
   },
   {
    path: 'autosuggest',
    component: AutosuggestComponent,
   },
   {
     path: 'manageCookies',
     component: ManageCookiesComponent,
   },
   {
     path: 'progressBar',
     component: ProgressBarComponent,
   },
 ];

If you want to add a custom class to the navbar based on the current route, for example, if the current route is progressBar, you can do this:

 <nav class="menu" [class.myClass]="currentRoute === 'progressBar'">
   .......
 </nav>

Answer №1

Leverage the router module by passing multiple classes in the routerLinkActive attribute. For a more comprehensive guide, refer here.

 <nav class="menu">
   <a routerLink="textArea" [routerLinkActive]="['is-active', 'class 1']" class="menu-item">text-area</a>
   <a routerLink="dropdown" [routerLinkActive]="['is-active']" class="menu-item">dropdown</a>
   <a routerLink="autosuggest" [routerLinkActive]="['is-active']" class="menu-item">autosuggest</a>
   <a routerLink="manageCookies" [routerLinkActive]="['is-active']" class="menu-item">manage-cookies</a>
   <a routerLink="progressBar" [routerLinkActive]="['is-active']" class="menu-item">progress-bar</a>
 </nav>

To dynamically handle this, consider the following approach:

 <nav class="menu" [ngClass]="urlBased">
   .......
 </nav>

In your TypeScript file, create a function to set urlBased according to the active route:

// Implement the following code
 constructor(private router: Router) {
          router.events.subscribe((url:any) => { 
          console.log(url)); // The URL will be the path or you can use this.router.url
          //this.urlBased = this.router.url;
          this.urlBased = url;
           if(this.urlBased && this.urlBased.length > 0){
            this.urlBased = this.urlBased.slice(1);
            if (this.urlBased == 'progressBar') this.urlBased = progressBar;
          }
   }
  }

Answer №2

Utilize the routerLinkActive attribute in conjunction with routerLink.

<a routerLink="home" [routerLinkActive]="['active-link']">Home</a>
<a routerLink="about" [routerLinkActive]="['active-link']">About</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to send a httpClient request when invoked prior to unloading

Having an issue with calling a function that listens to the event onBeforeUnload() and trying to post data using an httpClient request. However, the request is not being sent correctly. Here's the code snippet: @HostListener('window:beforeunlo ...

What sets apart a JSON Key that is enclosed in double quotes "" from one that has no quotes?

Below is my TypeScript object: { first_name:"test", last_name: "test", birthdate:"2018-01-08T16:00:00.000Z", contactNumber: "12312312312", email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e19 ...

Angular Delight: Jaw-Dropping Animation

After setting up my first Angular project, I wanted to incorporate Angular Animations to bring life to my content as the user scrolls through the page. I aimed to not only have the content appear on scroll but also implement a staggering animation effect. ...

Ways to showcase information based on the chosen option?

Is there a way to display data based on the selected value in a more efficient manner? Currently, when clicking on a value from the list on the left side, new data is added next to the existing data. However, I would like the new data to replace the existi ...

Guide to connecting data from the backend to the frontend in the select option feature using Angular 9

I have a backend system where I store a number representing a selected object, which I am trying to display in a select option using Angular. Currently, the select option only displays a list of items that I have predefined in my TypeScript code using enu ...

The expected rendering of column headers was not achieved following the refactoring of <Column />

After making changes, the header is not rendering properly and I cannot see the "Product ID" header for the column: // DataTable.tsx // React Imports import React, { useState } from 'react'; // PrimeReact Imports import { DataTable as DT } from ...

Angular2 Release Candidate 1 Pipes Introducing Unexpected Undefined Results

Upon upgrading to RC1 from Beta, it appears that the pipes are not effectively passing data. The error I am encountering is as follows: ORIGINAL EXCEPTION: TypeError: Cannot read property '1' of undefined ORIGINAL STACKTRACE: TypeError: Cannot r ...

Developing Angular 7 Forms with Conditional Group Requirements

I am currently in the process of developing a form that enables users to configure their payment preferences. The form includes a dropdown menu where users can select their preferred payment method. For each payment method, there is a FormGroup that co ...

The instance is referring to a property or method that is not defined, but being used during rendering. Verify that the property is reactive and included in the data option

I'm a newcomer to vue JS and facing a challenge with creating vue class components. My setup includes: @rails/webpacker: "^5.1.1" typescript: "^4.0.2" vue: "^2.6.11" vue-class-component: "^7.2.5" Below is the ...

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

The process of generating a date is not considering the provided date range

When I use an input type date in Angular 4 with two Date picker fields, the issue arises when I select a range of dates and press save. Instead of saving the selected dates, it is saving the current date. I have tried using ngModelChange to update the valu ...

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...

When implementing React Context within a custom hook, the output is consistently undefined

I am currently in the process of developing a custom hook that will be packaged and utilized internally on projects within the company I am employed at. The main concept behind this package is to have a provider that, when mounted, will make a server reque ...

Encountering a 404 error while attempting to test a contact form on a Next.js website using a local server

Trying to test a contact form in Next.js where the data is logged but not sent to the API due to an error. "POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)" Troubleshooting to identify the issue. [directory setup] ...

Exploring the functionality of Material components within a nested child component

I am facing an issue with my TestComponent, which uses a <mat-stepper> in its template. Due to the specific context of the stepper, I have to programmatically move to the next step instead of using the matStepperNext directive on a button. Here is a ...

Using TypeScript for event handling in JointJS

I am facing a challenge in adding an event handler for jointjs paper using TypeScript. I have been unable to find a way to implement it with the joint.js definition file. private paper = new joint.dia.Paper({ el: $('#paper'), ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

Error: Unable to access properties of null (specifically 'writeValue')

My goal is to retrieve an object by its ID, and if the object does not exist, the component will then register the object. However, when the object does exist, it retrieves the object normally, but then throws the same error again. HTML: <div class="c ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...