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

72
Visualizações
Add a class on item selection and remove it to add on another element selection

I have a table that shows me a list of item. I want to be able to add a class on the selected item and remove it when I select another one.

Here's my template:

<div class="row">
  <div class="col-10 pl-3">
    <h1>My Shopping List</h1>
    <h3 class="mb-0">Add all the ingredients you need</h3>
    <app-shopping-edit></app-shopping-edit>
    <table>
      <tr>
        <th>Ingredient</th>
        <th>Amount</th>
      </tr>
      <tr
        *ngFor="let ingredient of ingredients; let i = index"
        (click)="onEditItem(i)"
      >
        <td>{{ ingredient.name }}</td>
        <td>{{ ingredient.amount }}</td>
      </tr>
    </table>
  </div>
</div>

Here's my ts code:

 onEditItem(index: number) {
    this.shoppingListService.startedEditing.next(index);
    this.addStyleOfSelection(event);
  }

  addStyleOfSelection(event: any) {
    let selection = event.target;
    let trSelected = selection.parentNode;
    trSelected.classList.toggle('selected');
  }

Also "event" is deprecated, but I can't figure out what to use instead.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you can do something like that

<div *ngFor="let item of items" [class.is-selected]="item === selectedItem" (click)="selectedItem = item">{{ item.name }}</div>
about 4 years ago · Juan Pablo Isaza Relatório

0

you can try another way also, *.html

<div
  *ngFor="let item of items; let idx = index"
  [ngClass]="{ selected: activeIdx == idx }"
  (click)="handleActiveRow(idx)"
>
  {{ item.name }}
</div>

and also *.ts file looks

  public activeIdx: number | null = null;
  public items: Array<any> = [{ name: 'hitee' }, { name: 'krish' }];

  public handleActiveRow(event: any) {
    this.activeIdx = event;
  }

and also *.css looks like,

.selected {
  background-color: blueviolet;
} 
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