Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda