2016-02-26 65 views
0

我試圖在按鈕按下時按下數組中的數據,並在按鈕再次按下一次(並更改按鈕類)時將其從數組中刪除。如何切換按鈕?

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

我把我的類中的兩種方法 - 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

我該怎麼辦呢? hasColor方法返回true或false,但從來沒有在onPress方法返回

回答

2

hasColor方法

不,它不返回true或false。

您傳遞給forEach的匿名函數返回truefalse(並且對循環中的每個項目都這樣做)。

hasColor函數根本沒有return語句。

如果要查看任何項目是否匹配for循環,則需要使用變量來跟蹤以查看是否有任何匹配,然後在循環結束後返回該變量。

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

非常感謝。我需要學習Javascript(((( – Slip