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.

2
  • you can refere stackoverflow.com/questions/42790602/… this link also Commented Aug 29, 2018 at 12:54
  • @AniketAvhad Thanks, really useful information :) Commented Aug 29, 2018 at 13:07

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thanks. Had no clue that JavaScript statement would work :)
"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!
0

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

<button [class.isSelected]="selectedArr.indexOf(item) != -1"></button>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.