我有一个表,每行包含一个复选框。在表格标题中,我有一个 Check All
复选框,用于切换所有表格行框。
我正在尝试实现一些逻辑,如果复选框的数量将超过特定限制,则显示错误并且不切换表行复选框或 checkall
框本身。
有一个问题允许选中 checkAll
框,即使我返回的是 false
。我的绑定(bind)有问题?
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;
会阻止这种情况,但我想不会。是不是我的绑定(bind)有什么问题导致它仍然可以切换?
最佳答案
ngModelChange
当绑定(bind)到复选框的值发生变化时被触发,停止切换操作已经晚了。
在这里你应该绑定(bind)click
事件。然后你可以使用 $event.preventDefault()
来阻止复选框被切换。
您可以在 $event.preventDefault()
之前添加一些逻辑来确定是否应阻止复选框更改状态。
参见 Plunker demo .
关于javascript - Angular2 - 防止复选框被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726725/