Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Prevent Checkbox from being checked

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?

like image 657
SBB Avatar asked Aug 17 '17 04:08

SBB


1 Answers

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.

like image 196
Pengyy Avatar answered Sep 23 '22 19:09

Pengyy