Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
OnClick check, remove & add class name in angular13

I want to add the class name 'active' onClick to 'li a' & also remove any 'active' class present on the 'li a'. The current code is working properly if I click sequence from top elements, but when I click elements from bottom to top, it's not working.

  1. component.html
<div class="container text-center">
  <ul id="myList" class="pt-5">
    <li class="p-3">
      <a href="#" class="d-inline-block" (click)="linkActive($event)">List 1</a>
    </li>
    <li class="p-3">
      <a href="#" class="d-inline-block" (click)="linkActive($event)">List 2</a>
    </li>
  </ul>
</div>
  1. component.ts
linkActive(event) {
    const activeClass = event.srcElement.classList.contains('active');
    const classFound = document.querySelector('li a');
    const hpn = classFound.classList.contains('active');
    if (activeClass == true) {
      if (hpn == true) {
        classFound.classList.remove('active');
      }
      alert('true');
      event.srcElement.classList.remove('active');
    } else {
      if (hpn == true) {
        classFound.classList.remove('active');
      }
      alert('false');
      event.srcElement.classList.add('active');
    }
  }

Please find the sample code : https://stackblitz.com/edit/angular-ivy-jf9xvp

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Do not manipulate the DOM directly like this, You can use ngClass to achieve the desired result:

template:

<a href="#" class="d-inline-block" [ngClass]="{'active': activeList === 1}" (click)="linkActive(1)">List1</a>

.ts

public activeList: number;

...

public linkActive(listNumber: number) {
   this.activeList = listNumber; 
}

In general, as recommended in comments, do the heroes tutorial and try to understand how to use typescript.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!