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

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

I'm curious, which redux architecture would you recommend for this specific scenario?

I'm currently developing an application and I'm facing a challenge in implementing Redux effectively in this particular scenario. Unfortunately, due to restrictions at my workplace, normalizing data is not an option. Let's consider the foll ...

Is there a way to automatically validate v-forms inside a v-data-table when the page loads?

In my data entry form, I have utilized a v-data-table with each column containing a v-form and v-text-field for direct value updates. My goal is to validate all fields upon page load to identify any incorrect data inputs. However, I am facing challenges in ...

String date in the format "dd-MM-yyyy" cannot be transformed into a date using the 'DatePipe' function

Having trouble with date conversion in my custom pipe. It seems that when using a locale of 'nl-nl' and trying to format the date as 'dd-MM-YYYY', I'm seeing an error message stating Unable to convert "16-02-2023" into a ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...

Navigating using ViewChild in Ionic 2 Beta

I recently updated my Ionic 2 app to use Angular 2 RC1, which has been a great improvement. However, I am facing some challenges with the routing implementation. Despite following the update guide, I still encounter issues with my navigation component bein ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

Angular: The object you supplied is not compatible with a stream. Be sure to pass in an Observable, Promise, Array, or Iterable instead

I'm currently working on implementing the Material autocomplete component with filtering using my own array of values. However, I encountered the following error: core.js:1624 ERROR TypeError: You provided an invalid object where a stream was expecte ...

Change the property value prior to running TypeScript validation

I possess the following object: const translations = { msg_hello: 'Hello', msg_bye: 'Bye' } In addition, I have a function that is structured as such: const generateTranslation = (partialKey: string): keyof typeof translations ...

Angular2 API call error: The function .map defaultOptions.merge is not recognized

When attempting to call the API using the post method, I encountered the following error message: this._defaultOptions.merge is not a function ... I looked into some solutions and tried importing the following without success: import 'rxjs/add/ope ...

Utilizing Angular to handle all your file uploading, storing, and downloading needs with base

I am currently working with Angular and attempting to upload a file to be stored in the database, and then download the file. I am utilizing base64 encoding/decoding for this process. It appears to be functioning correctly, however, when I try to open the ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Creating Algorithms for Generic Interfaces in TypeScript to Make them Compatible with Derived Generic Classes

Consider the (simplified) code: interface GenericInterface<T> { value: T } function genericIdentity<T>(instance : GenericInterface<T>) : GenericInterface<T> { return instance; } class GenericImplementingClass<T> implemen ...

Rendering a React/Material UI class based on the state variable in a conditional manner

I am currently working on building a basic navbar setup using React and Material UI. I have encountered an issue where React-Router-Dom does not seem to be functioning within this particular project, and implementing it would be excessive for the simple ta ...

What is causing the error "has no properties in common with" in this wrapped styled-component?

When looking at the following code, Typescript is flagging an error on <HeaderInner>: [ts] Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & Pick & Partial>, "className"> & ... ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...

Binding user input to a preset value in Angular with data binding

My goal is to have a predefined input form with the email provider value preset. However, when I try to submit the form without modifying it, it does not upload anything to Firebase unless I manually delete the value and re-enter it. <input class="butt ...

Can the dragging functionality be turned off for a specific sub-element of cdkDrag?

Currently, I am utilizing Angular CDK drag-drop features from Angular Material. I have been exploring the documentation available here. One issue that has arisen is the inability to select text within an input field of a draggable element using the mouse. ...