2

I'm trying to trigger a class if the item exist inside the array, but I can't figure it out.

  <div *ngFor="let item of someList">

     <button [ngClass]="{'isSelected': selectedArr contains item}"></button>
    ..

selectedArr is the array that contains some item.

Skyan
  • 71
  • 1
  • 6

2 Answers2

6

selectedArr.includes(item) will work. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Note that if item is an object, selectedArr will have to have the same object, not just an object with the same properties. Otherwise you'll have to find a different way to compare the properties of the objects to see if there's a match. Anyway, any valid JavaScript statement can be used as the value for isSelected.

<button [ngClass]="{'isSelected': selectedArr.includes(item)}"></button>
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Awesome, thanks. Had no clue that JavaScript statement would work :) – Skyan Aug 29 '18 at 13:07
  • "Note that if item is an object, selectedArr will have to have the same object, not just an object with the same properties." Thanks for pointing this out, was having some trouble comparing until I saw this, thanks! – Jacklyn Lim Apr 05 '22 at 09:17
0

Use can use [class.className] also to do the same.

<button [class.isSelected]="selectedArr.indexOf(item) != -1"></button>
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21