update icon when a router link becomes active

<div class="menuItem mb-3" *ngFor="let menuItem of menuItems">
    <a routerLink="{{menuItem.link}}" routerLinkActive="active">
        <img src="{{menuItem.icon}}" alt="{{menuItem.name}}" />
        <p class="text-center f-12">{{menuItem.name}}</p>
    </a>
</div>

When the router link is active, I would like to update {{menuItem.icon}} to {{menuItem.iconAtv}}

Answer №1

Give this a shot:

<a routerLink="{{menuItem.link}}" routerLinkActive="active"  #rla="routerLinkActive">
        <img src="{{rla.isActive ? menuItem.icon : menuItem.iconAtv}}" alt="{{menuItem.name}}" />
        <p class="centered-text f-12">{{menuItem.name}}</p>
 </a>

Answer №2

Here is a way to do it:

<a routerLink="{{menuItem.link}}" routerLinkActive="active"  
#rla="routerLinkActive">
        <img src="{{rla.isActive ? menuItem.icon : menuItem.iconAtv}}" alt=" 
{{menuItem.name}}" />
        <p class="text-center f-12">{{menuItem.name}}</p>
 </a>

Answer №3

When incorporating the following code into your HTML:

<a mat-list-item *ngFor="let link of links" routerLink={{link.path}} routerLinkActive="active" >
   <img  [src]="router.url === ('/' + link.path) ? link.activeIcon : link.inactiveIcon"/>         
   <p>{{ link.label }}</p>
</a>

In your TS file, include the following:

links: any = [{
 inactiveIcon:'assets/images/icons/master-navigation/home-inactive.svg',
 activeIcon:'assets/images/icons/master-navigation/home-active.svg',
 label: 'Home',
 path: 'network'
}] 
constructor(public router: Router) {}

Answer №4

After much searching, I was able to find the solution for implementing this functionality...

The key is to define

#dashboard="routerLinkActive"
, which allows us to access the isActive attribute in the dashboard element.

Take a look at the code below with a calm mind! :)

<div class="top-tabs" id="app-sidebar-scrollbar">
    <div class="sidebar-item">
        <a class="sidebar-link" [routerLink]="['/worklists/dashboard']" routerLinkActive="active" #dashboard="routerLinkActive">
            <img [src]="dashboard.isActive ? 'assets/svg/sidebar-icons/dashboard-active.svg' : 'assets/svg/sidebar-icons/dashboard.svg'" />
            <span>Dashboard</span>
        </a>
    </div>
    <div class="sidebar-item">
        <a class="sidebar-link" [routerLink]="['/worklists/tasks-board']" routerLinkActive="active" #worklist="routerLinkActive">
            <img [src]="worklist.isActive ? 'assets/svg/sidebar-icons/goal-workflow-active.svg' : 'assets/svg/sidebar-icons/goal-workflow.svg'" />
            <span>Worklists</span>
        </a>
    </div>
    <div class="sidebar-item">

        <a class="sidebar-link" [routerLink]="['/assessment-requests/privacy']" routerLinkActive="active" #assessment="routerLinkActive">
            <img [src]="assessment.isActive ? 'assets/svg/sidebar-icons/assessments-active.svg' : 'assets/svg/sidebar-icons/assessments.svg'" />
            <span>Assessments</span>
        </a>
    </div>
</div>

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

Tips for avoiding sending empty fields when using Angular's HttpClient.post method

Whenever I try to send data using the POST method to my Rest API in Angular, it ends up sending empty fields resulting in my database storing these empty values. I want to find a way to stop this from happening so that no empty fields are sent from Angula ...

Tips for efficiently constructing a Docker container using nodejs and TypeScript

Struggling for the past couple of days to get the project running in production, but it keeps throwing different errors. The most recent one (hopefully the last!) is: > rimraf dist && tsc -p tsconfig.build.json tsc-watch/test/fixtures/failing.t ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Combining HTTPHandler Observable with another in HTTPInterceptor (Angular 8)

In our Angular 8 project, we have set up our API so that the response includes both a "data" attribute and an "errors" attribute. It's possible for there to be data as well as errors in the response, and we need access to both in the calling component ...

Disabling the scrollbar within angular elements

Trying to remove the two scrollbars from this code, but so far unsuccessful. Attempted using overflow:hidden without success filet.component.html <mat-drawer-container class="example-container" autosize> <button type="button&qu ...

A guide to building a versatile component using Ionic 3 and Angular 4

I decided to implement a reusable header for my app. Here's how I went about it: First, I created the component (app-header): app-header.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-header', te ...

Issue with RouterLink functionality in Angular 6

While following a Brad Traversy tutorial on coding, I implemented the instructions exactly as given. Below is my 'app.module.ts' file. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/c ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...

What is the process for transferring files from a NodeJS website to Azure CDN?

I am searching for a solution to upload images directly to Azure CDN. Here is the situation: My client Portal built with Angular (4.x) enables users to manage their website, and they need the capability to upload images that will be displayed on the sit ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

What is the process to activate/deactivate a drop-down menu once a radio button has been chosen

JSON Data: radio1Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, { value: 'col-2', viewValue: 'Col-2' } ]; radio2Data: any[] = [ { value: 'col-1', viewValue: 'Col-1' }, ...

What is the best method for incorporating a private key into a service without exposing it in the front-end code?

I am currently working on incorporating a private API key into a service by fetching it from a secure endpoint on the server. However, I am unsure of the correct approach to integrate this key into the required service. Confession time - I'm feeling ...

What is the best way to implement multiple HTTP subscriptions in a loop using Angular?

I find myself in a predicament where I need to iterate through an array of strings passed as parameters to a service, which then responds through the HTTP subscribe method. After that, some operations are performed on the response. The issue arises when t ...

Typescript: Utilizing Index-Based Callback Parameters in Functions

I am currently working on creating a function that can handle specific data types ("resource") along with an array of arrays containing call objects and corresponding callbacks for when the calls finish ("handlers"). function useHandleResource< R exte ...

Incorporating node packages into your typescript projects

I have been exploring various discussions on this forum but I am still unable to make it work. My goal is to compile the following code in TypeScript. The code is sourced from a single JavaScript file, however, due to issues with module inclusion, I am foc ...

There seems to be an issue with the compatibility between typescript and the current version (4.17.14) of the express-serve-static

Using "@types/express-serve-static-core": "4.17.13", the augmentation of express-serve-static-core is functioning properly: import { Request, Response, NextFunction } from 'express' import { PrismaClient } from '@prisma/c ...

`Inconsistencies in console.log output with Angular Firestore``

I'm currently working on retrieving the id of selected data, but when I test it using console.log, it keeps outputting twice. The image below illustrates the console.log output. https://i.stack.imgur.com/IARng.png My goal is to fetch the id once and ...

When compiling to ES5, TypeScript fails to remove imports

I am working on a TypeScript file that utilizes the moment library, and I need to import moment for it to compile properly. However, after compilation, the import line is still present in the compiled file, which is causing issues on my web page. Here is ...

Verify that the lower limit is not higher than the upper limit set in an Angular application

In my Angular application, I have two input fields for minimum and maximum values. I want to display an error message if the user enters a minimum value greater than the maximum value provided, or the default maximum value if none is provided. The form is ...

Angular FormControl is a built-in class that belongs to the Angular forms module. It

I’ve been working on adjusting tslint for the proper return type, and here’s what I have so far: get formControls(): any { return this.form.controls; } However, I encountered an error stating Type declaration of 'any' loses type-safet ...