Slip
Slip

Reputation: 949

How to toggle button?

I am trying to push a data in array when button pressed and delete it from array when button pressed one more time (and change the button class).

<button 
    *ngFor="#color of colors"
      [class.selected]="color === selectedColors"
      (click)="onPress(color)">
      {{color.name}}
</button>

I put a two methods in my class - onPress & hasColor

onPress(color: Color) {
this.selectedColors = color;
  // ckecking color in array
 if (this.hasColor(this.colorsArray,this.selectedColors.id)) {  
        //need to splice a color from array and change background color to default (to blue color)    
 } else {       
    // if not in colorsArray then push and change class to .selected
   this.colorsArray.push(this.selectedColors.id);
                         }
            } 

 hasColor(arrayC,id) {
      arrayC.forEach(function(item) {
    if (item === id) {
          return true;
        }
          return false;            
      });
    } 

Plunker

How can i do it? hasColor method returns true or false but in never returns in onPress method

Upvotes: 0

Views: 74

Answers (1)

Quentin
Quentin

Reputation: 943142

hasColor method returns true or false

No, it doesn't.

The anonymous function you pass to forEach returns true or false (and does so for every item in the loop).

The hasColor function doesn't have a return statement of its own at all.

If you want to see if any item matches in your for loop, then you need to use a variable to track to see if you have any matches, and then to return that variable after the loop ends.

hasColor(arrayC, id) {
    var match = false;
    arrayC.forEach(function(item) {
        if (item === id) {
            match = true;
        }
    });
    return match;
}

Upvotes: 2

Related Questions