Instructions for deselecting the active class from a previously selected list item when a new one is selected in Angular

How can I remove the intentionally set active class from a list item when other items are clicked, while still keeping it active on page load using routerLinkActive="active" in Angular?

I attempted to use ngClass but it did not work as expected. Is there a way to achieve this without relying on jQuery?

<ul class="nav"> 
       <li routerLinkActive="active" *ngFor="let menuItem of menuItems" [ngClass]="{'active': selectedItem == menuItem}" (click)="listClick($event, menuItem)">
         <a class="nav-link" [routerLink]="[menuItem.path]">
         <p>{{ menuItem.title }}</p>
        </a>
       </li>
     </ul>

declare interface RouteInfo {
  path: String,
  title: String,
  class: String
}
export const ROUTES: RouteInfo[] = [
  { path: '', title: 'Dashboard', class: '' },
  { path: '/vessel', title: 'Vessel Details', class: '' },
  { path: '/arrival', title: 'Arrival Details', class: ''},
  { path: '/stock', title: 'StockYard', class: ''},
  { path: '/cargo', title: 'Cargo Details', class: '' },
  { path: '/other', title: 'Others', class: ''}

];

menuItems: any[];
  selectedItem= false;

listClick(event, newValue) {
    console.log(newValue);
    this.selectedItem = !this.selectedItem;

  }

The active class that was intentionally set should be disabled when another list item is clicked.

Answer №1

After understanding your objective, it appears that using ngClass or the click event may not be necessary. Angular has the functionality to compare the active route with the routerLink path and apply the specified class in ActiveRouterLink accordingly.

To address your issue more effectively, consider adding [routerLinkActiveOptions]="{exact: true}" to the li element.

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

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

Icons from Material Design Lite are not appearing as expected when integrated into an Angular project

Recently, I integrated MDL into my Angular project. While most of it is functioning properly, the MDL icons seem to be giving me trouble... I've implemented them using <i class="material-icons">share</i>, but instead of displaying as an i ...

Is there a way to modify Style Properties in JavaScript by targeting elements with a specific class name using document.getElementsByClassName("Class_Name")?

I am seeking a solution to change the background color of multiple div boxes with the class name "flex-items" using JavaScript. Below is my current code: function changeColor(){ document.getElementsByClassName("flex-items").style.backgroundColor = "bl ...

Error in altering element width dimension

For my Bootstrap card project, I have some specific rules in mind: The card should have a minimum width of 250px (card #1 - looks good) If the first line exceeds 250px in length, the card should increase its width without wrapping the line (card #2 - widt ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element? Here is the code I am using: $(".menu_list_item").css({ width: width + "%" }); Unfortunately, this doesn't appear to be functioning correctly. If anyo ...

Angular Module without any components

The Angular modules documentation provides an example of a module that includes a template, a component, and a provider. This module is then imported into the root module and instantiated by using the element defined by the component like this: <app-co ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Grid item overlay

Currently, I am facing an issue with React where I am attempting to place an overlay on top of each grid item in a grid. Despite trying multiple approaches, the overlay appears beneath each grid item instead of over it. Even setting the position: absolute ...

What is the most recent stable version of Angular recommended for utilizing ui-bootstrap?

I've been working on updating an older angular application and I'm interested in incorporating ui bootstrap for more advanced features. However, the current version of Angular used is 1.2.18 and any attempt to upgrade it to a higher version resul ...

In an array where the first 3 images have been filtered using an if statement, how can I show the image at the 3rd index (4th image) starting from the beginning?

In my personal web development project, I'm using AngularJS for the front-end and .NET Core for the back-end to create a website for a musical instrument retailer. The model I'm working with is called "Guitar" and all the guitar data is stored in ...

Pay attention to the input field once the hidden attribute is toggled off

In attempting to shift my attention to the input element following a click on the edit button, I designed the code below. The purpose of the edit is to change the hidden attribute to false. Here's what I attempted: editMyLink(i, currentState) { ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...

Linking enumeration value to an Angular material table

Is it possible to associate enum values with an Angular Material table? For instance, I have defined an enum: export enum EnumName { val1 = 1, val2 = 2, val3 = 3 } and I want the Angular Material table to display it like this: Id EnumNameColumn ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

Having trouble setting a default value within an Angular component using ControlValueAccessor?

Demo: https://plnkr.co/edit/cMu3lI3PkxHRErJE3T93?p=preview I've encountered an issue with setting default values for ngModel or formControlName when using ControlValueAccessor in multiple components. For instance, in the provided demo, there is a se ...

NgFor in IONIC4 can only bind to Iterables like Arrays

Hello everyone, I am facing an issue in my code: it is displaying the error: (ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.) I am trying ...

Can simply adding Bootstrap CDN make a website responsive?

Is Bootstrap truly self-sufficient when it comes to responsive design, or do custom webpages utilizing Bootstrap require additional responsive instructions? If I incorporate the Bootstrap CDN and utilize its built-in components, can I assume the webpage ...

What is the best way to create a sticky/fixed navbar that conceals the div above it while scrolling on the page?

When I am at the top of the page, I want to display the phone number and email above the navigation bar. However, as soon as I start scrolling down, I want the phone number and email to disappear and only show the navigation bar. I have attempted using fix ...

Link various data to various text boxes using a common ngModel property in Angular 8

In my project, I am working on creating a time-picker that will open when the user focuses on a text-box. The challenge I'm encountering is that although there are multiple text-boxes on a single page, binding the selected value from the time-picker u ...