When a list item is clicked, the 'active' class is added to it and removed from its sibling elements in Angular 8

By default, the first list item will be active. When you click on any list item, it should add a class of 'active' and remove the class from its siblings.

public items = [{
    value: 'All',
  },
  {
    value: 'Photos',
  },
  {
    value: 'Video',
  },
];
li .active {
  color: red;
}
<div *ngFor="let item of items" class="nav-li">
  <ul>
    <li class="value" [value]="item.value"><a href="">{{item.value}}</a></li>
  </ul>

</div>

Answer №1

To dynamically toggle the class based on the clicked index, you can save the index in a variable and adjust the class accordingly. Here's an example:

<div class="nav-li">
  <ul>
    <li *ngFor="let item of items; let i = index" 
    [ngClass]="{'active': selectedItem === i}"
    [value]="item.value" 
    (click)='selectedItem = i;'>
      {{item.value}}
    </li>
  </ul>
</div>

selectedItem = 0;

Check out a working example here.

Tip: If not necessary, consider iterating the *ngFor directly on the li element instead of wrapping it in a DIV. This approach would reduce unnecessary repetition of div, ul, li elements for each iteration, making your DOM more efficient.

Answer №2

.ts

    const categories = [{
        name: 'All',
        status: 'active'
      },
      {
        name: 'Photos',
        status: ''
      },
      {
        name: 'Video',
        status: ''
      },
    ];
    
    function updateStatus(index) {
      categories.map((category, categoryIndex) => {
        index === categoryIndex ? category.status = 'active' : category.status = '';
        return category;
      })
    }

.html

<div *ngFor="let category of categories; index as i" class="nav-li">
  <ul>
    <li [class]="category.status" (click)="updateStatus(i)"  [value]="category.name"><a href="javascript:void(0);">{{category.name}}</a></li>
  </ul>

</div>

Answer №3

Check out this code snippet with the href tag removed:

<div *ngFor="let item of items; let i = index" class="nav-li">
    <ul>
        <li class="value" [ngClass]="getActiveClass(i)" [value]="item.value" 
           (click)="setActiveIndex(i)">
           <a>{{item.value}}</a>
        </li>
    </ul>
</div>

.ts

  var activeIndex;

  setActiveIndex(index) {
    this.activeIndex = index;
  }

  getActiveClass(i) {
    return this.activeIndex == i ? 'active' : '';
  }

.css

.active {
  color: red;
}

Answer №4

    **HTML**
    <div *ngFor="let element of elements; let idx=index" class="nav-box">
      <ul>
        <li class="{{activeIndex==idx ? 'active':''}}" [value]="element.value"><a href="#" (click)="toggleSelection(idx)">{{element.value}}</a></li>
      </ul>
    </div>
    
    **Typescript**
     toggleSelection(index){
        this.activeIndex = index;
      }

**CSS**

.active {
  color: blue;
}

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

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...

Enhancing Error Validation Messages in FormControl to Include More Specific Details

In continuation of my previous inquiry, my objective is to display a customized error message for user inputs. Instead of presenting users with a generic error message, I want to provide them with specific feedback. For example, if the input field only al ...

How do I manage two components on the same routing level in Angular with query parameters?

I am working with Angular and have two components placed at the same level of routing, both in the root directory. { path: '', component: HomeComponent }, { path: '', component: SearchComponent }, My challenge is to mak ...

Having trouble with code behaving differently than expected in Chrome's debugger

I've come across a peculiar issue in my TypeScript project (an Angular application). Here's the code snippet that's causing trouble: const idx = myclone.findIndex(x => x.id === action.id); const hasVal = idx>-1; // for some reason, Chr ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...

Can you explain the concept of interface with dual function type declarations and provide guidance on its implementation?

interface MyInterface { (choose: string): number; (item: number): string; } Can you provide guidance on using the MyInterface interface mentioned above? How would it be helpful in practical situations? ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Exploring Angular Testing with SpyOn

Apologies for my inexperience with Angular, but I am struggling with using spyOn in a unit test. In my unit test, there is a method on the component that calls service1, which in turn calls another service2. However, when I try to spyOn service1 in order ...

Error: Unable to access 'match' property of an undefined value

After upgrading my Angular application from version 12 to 13, I encountered an error during unit testing. Chrome Headless 94.0.4606.61 (Windows 10) AppComponent should create the app FAILED TypeError: Cannot read properties of undefined (reading &a ...

React: Retrieved information, yet unable to access the properties of the object

After successfully fetching data from an API call and seeing the results in console, I am facing issues with accessing object properties and displaying them. interface Data { data: [] isLoading: boolean } function About() { const [ dataUser, ...

The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hi ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

waiting for the import statement in a React/NextJS/Typescript project to resolve

While working on my node.js development server, I encountered a problem with the following code: import { useRouter } from 'next/router' import nextBase64 from 'next-base64'; const Load = () => { const router = useRouter() co ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...