0

I want to bind a result of a function inside my [ngClass] condition, but it's simply not doing anything.

HTML

<div [ngClass]="{hover': check(token.ids)}" *ngFor="let tokens of info.data">  

I trying to return a boolean from the function and nothing happens, but When I log it inside the console I receiving true or false value depending on the passed elements.

check(tokens) {
    tokens.forEach(token => {
      if (token.id === this.currentToken) {
        return true
      }
    });
  } 
Igor.ro
  • 37
  • 2
  • 9
  • try `[ngClass]="{ hover: check(token.ids) }` – The Head Rush May 13 '19 at 14:47
  • `return true` returns true from the function passed to `forEach`, not the `check` function. Instead return the result of calling `some` on `tokens`. – Heretic Monkey May 13 '19 at 14:48
  • Possible duplicate of [What does \`return\` keyword mean inside \`forEach\` function?](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – Heretic Monkey May 13 '19 at 14:49
  • as @HereticMonkey said, but you also need to check your variable names : the loop declares a `tokens` while you pass in a `token`. –  May 13 '19 at 14:49
  • @HereticMonkey Can you please write a small example. Thank you – Igor.ro May 13 '19 at 14:50
  • Please read the answers to the duplicate, and the answers to [Can forEach in JavaScript make a return?](https://stackoverflow.com/q/32041912/215552) – Heretic Monkey May 13 '19 at 14:52
  • Possible duplicate of [Short circuit Array.forEach like calling break](https://stackoverflow.com/questions/2641347/short-circuit-array-foreach-like-calling-break) – Friso Hoekstra May 13 '19 at 15:02

2 Answers2

1
 check(tokens) {
    let res = false;
    tokens.forEach(token => {
       if (token.id === this.currentToken) {
         res = true
       }
    });
    return res;
 } 

Your check function is not returning a value and it will return undefined as a value. So you could do it this way where you are returning back value by declaring it in the function..

hafridi
  • 258
  • 3
  • 9
0

Short circuit Array.forEach like calling break

Try this

  check(tokens) {
      const match = false;
      tokens.forEach(token => {
        if (token.id === this.currentToken) {
          match = true
        }
      });
      return match;
   } 
Friso Hoekstra
  • 845
  • 2
  • 9
  • 24
  • Your code works, but I'm a bit puzzled about the stackoverflow link you posted. Your solution won't short circuit, it will iterate through all tokens even if a match is found. It's better to use `match = tokens.some(token => token.id === this.currentToken)` performance-wise (although marginally if there are few tokens). – ShamPooSham May 14 '19 at 13:21
  • The point I am trying to make that OP’s function doesn’t return anything because return inside a forEach loop doesn’t actually break the loop. – Friso Hoekstra May 14 '19 at 13:34