Angular2 - Prevent Checkbox from being checked

SBB picture SBB · Aug 17, 2017 · Viewed 11k times · Source

I have a table that contains a checkbox per row. In the table header, I have a Check All checkbox that toggles all of the table row boxes.

I am trying to implement some logic to where if the count of checkboxes are going to exceed a specific limit, show an error and don't toggle the table row checkboxes OR the checkall box itself.

There is an issue that is allowing the checkAll box to get checked, even though I am returning false. Issue with my binding?

HTML:

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

Component:

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.
    }
}

Although none of the table row check boxes get checked, and the error is shown appropriately, the box I am clicking on still gets toggled.

I assumed that the return false; would have prevented that but I guess not. Is there something wrong with my binding that is allowing it to be toggled anyway?

Answer

Pengyy picture Pengyy · Aug 17, 2017

ngModelChange is fired when value binded to checkbox has changed, it's late for stop the toggle operation.

Here you should bind with click event. Then you can use $event.preventDefault() to stop checkbox from been toggled.


You can event add some logic before $event.preventDefault() to determin whether the checkbox should be prevent from changing status.

see Plunker demo.