2017-08-17 118 views
1

我有一個表,每行包含一個複選框。在表格標題中,我有一個用於切換所有表格行框的Check All複選框。Angular2 - 防止複選框被檢查

我想實現一些邏輯,如果複選框的計數將超過特定限制,顯示錯誤並且不切換表格行復選框或checkall框本身。

存在一個問題,即允許checkAll框被檢查,即使我返回false。問題與我的約束?

HTML:

<input type="checkbox" name="checkAll" [(ngModel)]="checkedAll" (ngModelChange)="toggleAllEmployees($event)"> 

組件:

toggleAllEmployees(flag) { 

    const temp = []; 

    if (flag) { 

     // If selecting all of these passes the max, throw an error 
     if (this.importResults.length > this.maxSelection) { 

      /* This is where I get to when I display the error message */ 
      alert('The number of employees you are trying to select (' + this.importResults.length + ') exceeds the max limit.'); 
      return false; 

     } else { 
      for (let i = 0; i < this.importResults.length; i++) { 
       if (this.importResults[i].OnTempAssignment !== 'True') { 
        this.importResults[i].checked = true; 
        temp.push(this.importResults[i]); 
       } 
      } 
      this.employeeSelection = temp; 

      // Emit our changes 
      this.selectedEmployees.emit(this.employeeSelection); 

     } 
    } else { 
     //The else statement just un-checks all the boxes. 
    } 
} 

雖然沒有任何的錶行複選框得到遏制,適當顯示的錯誤,我點擊框仍然被切換。我認爲return false;會阻止,但我猜不是。無論如何,我的綁定有什麼問題嗎?

+0

您是否嘗試過'event.preventDefault();' – Aravind

+0

@AravindI確實沒有這樣做。 '$ event'只是發送一個true/false布爾值,而不是一個實際的事件對象。 – SBB

+0

你也可以使用[**指針事件css **](https://developer.mozilla.org/en/docs/Web/CSS/pointer-events) – Aravind

回答

2

ngModelChange當綁定到複選框的值發生更改時會觸發,因此停止切換操作已晚。

在這裏你應該綁定click事件。然後,您可以使用$event.preventDefault()停止切換複選框。


您可以事件$event.preventDefault()前添加一些邏輯來determin是否複選框應該從改變狀態來防止。

參見Plunker demo

+0

謝謝,這幫助我解決了我的問題。 –