Implementing routerLinkActive for the same link in multiple sections in Angular

I am facing an issue with the routerLinkActive class in my application. I have two sections, one for pinned tools and one for all tools. Both sections have the same routerLink defined. The problem is that when I click on a link in the pinned tools section, the routerLinkActive class is applied to both the pinned tools and all tools sections. I want the routerLinkActive class to be applied only to the clicked link in the pinned tools section.

Here is the code for the All Tools section:

<ul class="dropdown-list" id="parentdrop{{i}}">
            <li class="custommy" *ngFor="let subitem of item.submenus; let j = index;" id="clickedSubMenu{{j}}" (click)="expandSubMenu($event,j,i)">
              <a [routerLink]="['/app/' + subitem.menu.split(' ').join('').replace('-','')]" [routerLinkActive]="['allToolsActive']" (click)="alltoolsCheckClick(subitem.id, subitem.menu)" id="clickedSMenu{{i}}">{{subitem.menu}}</a>
            </li>

          </ul>

And here is the code for the Pinned Tools section:

 <div id="{{sub.id}}" class="pinnedtools__list" [routerLink]="['/app/' + sub.menu.split(' ').join('').replace('-','')]" [routerLinkActive]="['active']" #rla1="routerLinkActive" (click)="pinnCheckClick(sub.id, sub.menu!==' '?sub.menu:sub.category)">

                <span>
                  <img src='{{ "/src/assets/icons/" + sub.category + ".svg" }}' class="pinnedmenu__img__icon" />


                </span>

                <div class="navList__subheading-title">
                  <span class="sub_category">{{sub.category}}</span>
                  <div>{{sub.menu}}</div>
                </div>

              </div>

Answer №1

It appears that achieving your desired outcome may not be possible in the way you are hoping for. The key is to ensure that as long as the target route remains active, it will apply the specified class to the element, allowing you to customize its appearance as needed.

If both options are connected to the route, they will both remain active while on that specific route.

To work around this issue, you may need to take matters into your own hands. One approach could involve keeping the duplicate active elements in place and adding a new class when one of those options is selected.

Subsequently, your CSS can respond accordingly depending on which option was clicked:

.active.clicked {
    background-color: red;
}
<a ... (click)="onToolsClick()" [class.clicked]="userClickedTools">Tools</a>
<a ... (click)="onPinnedToolsClick()" [class.clicked]="userClickedPinnedTools">Pinned Tools</a>
public onToolsClick(): void {
    this.userClickedTools = true;
    this.userClickedPinnedTools = false;
}

public onPinnedToolsClick(): void {
    this.userClickedTools = false;
    this.userClickedPinnedTools = true;
}

Does this solution align with what you had in mind?

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

When the query result is received in Angular TypeScript, translate epoch time into a time string

Here is the dilemma I am currently facing: I have an Angular script that requests data from a backend service and receives query results to display to the user. One of the fields in the query response is a time stamp, which is currently in epoch time forma ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Unable to locate module '@angular/core' while utilizing PrimeNG

After installing PrimeNg, I attempted to use the sidebar component in my project. However, upon running the project, an error occurred: ERROR in /home/haddad/projects/node_modules/primeng/components/sidebar/sidebar.d.ts (1,97): Cannot find module '@a ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

Ignoring the NGRX Store selector override during testing appears to be happening

When overriding the selector to return null, the data is still returned as per the override set during initialization. Attempting to use setState did not yield results either. Testing the else condition in the following code block: this.store.pipe(select( ...

What is the best way to test a local variable in Angular 2 using karma and jasmine?

I've been working on writing a unit test with jasmine, but I've run into an issue when trying to test a local variable using jasmine. I have successfully tested a global variable in the past, but testing a local variable seems to be more challeng ...

Guide to Generating a Library Using Angular-CLI

Can someone guide me on creating a custom Angular library using angular-cli and publishing it to the npm repository? I need to include other external libraries and expose my module along with some services in the index.ts file. Could you please provide s ...

I want to remove an object from my Django Rest Framework (DRF) database using Angular 13

After receiving the id that needs to be deleted, I noticed that the last line of code in service.ts for the delete method is not being executed. The files and code snippets I utilized are: COMPONENT.HTML <li *ngFor="let source of sources$ | async ...

When compiling for production, I am encountering an issue where the hashed files are resulting in 404 errors for users when they try to refresh. I am unsure of the best

My Angular app is hosted on GCP storage. When I use the command ng build --prod --base-href . --output-path ~/Dev/GCP/, everything works perfectly except for one issue. If a user refreshes to get new content, they encounter 404 errors on CSS and JavaScript ...

Bring in d3 along with d3-force-attract

Recently, I have installed D3 along with d3-force-attract. npm install @types/d3 -S npm install -S d3-force-attract I am currently facing an issue with importing d3 force attract as it is not recognized as a typescript module, unlike d3 itself. The inco ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Setting default selections for mat-select component in Angular 6

I've been attempting to preselect multiple options in a mat-select element, but I haven't been successful so far. Below is the snippet of HTML code: <mat-dialog-content [formGroup]="form"> <mat-form-field> <mat-select pla ...

Move the files created by ng build in the specified output directory to a different location

I am facing an issue with my Angular project. Whenever I run the ng build command, the build artifacts are generated in the dist folder as we have specified "outDir": "dist" in angular-cli.json. However, I then have to manually copy these files from the di ...

Error: Unable to perform operation on undefined object when trying to map over 'reminder' object

I've been struggling with my reminder-list.tsx file. No matter how many times I try to fix it, I always end up failing. Can someone help me figure out how to resolve this issue? Every time I run the code, I get the TypeError: undefined is not an obje ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

What is the best way to forward all URLs to one central page?

I've recently started working with Angular and I'm currently developing a web app project using Angular 9. I could really use your help with this. My goal is to have a dynamic URL structure for the web app, such as https://www.myMainURL.com/***, ...

Problem: Angular's HttpClientModule is not defined

I am encountering an issue with the HttpClientModule while trying to load this ModuleType in Angular. The error message I receive is related to the registerNgModuleType method. function registerNgModuleType(ngModuleType) { if (ngModuleType.ɵmod.id != ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

Angular 10 Error: API Module Redundancy Detected

My current issue lies with the ApiModule generated by Swagger. Despite providing it only once in my AppModule, it appears to be created twice, causing the application to fail due to a constructor guard: export class ApiModule { public static forRoot(co ...