我有一个表,每行包含一个复选框。在表格标题中,我有一个 Check All
复选框,用于切换所有表格行框。
我正在尝试实现一些逻辑,如果复选框的数量将超过特定限制,则显示错误并且不切换表行复选框或 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;
会阻止这种情况,但我想不会。我的绑定有什么问题导致它仍然可以切换吗?
原文由 SBB 发布,翻译遵循 CC BY-SA 4.0 许可协议
ngModelChange
当绑定到复选框的值发生变化时触发,停止切换操作已经晚了。在这里你应该绑定
click
事件。然后您可以使用$event.preventDefault()
来停止切换复选框。您可以在事件之前添加一些逻辑
$event.preventDefault()
以确定是否应防止复选框更改状态。请参阅 Plunker 演示。