angular - angular2+:如何遍历三态(不确定)复选框的值
问题描述
我使用 Angular 2+,bootstrap4,没有 jQuery
复选框需要具有三种状态的原因是因为我们使用它在后端执行查询(作为多个条件之一),如下所示:
- true:所有已售出的物品
- false:所有未售出的商品
- null:不使用此标准进行过滤
我设法用不确定的初始值初始化复选框:
- html.component:
<input class="form-control" type="checkbox" formControlName="issold" (change)="onCheckboxIssoldChange($event)"
[indeterminate]="true" #issold>
- ts.component
set indeterminate(value: boolean) {
this.elem.nativeElement.indeterminate = value;
}
为了遍历这些值,我尝试了两种方法:
- 使用 ElemenRef
constructor(private elem: ElementRef) {}
indeterminateCounterSold : number = 0;
@ViewChild('issold', { static: true }) issold: ElementRef;
onCheckboxIssoldChange(e) {
this.indeterminateCounterSold++;
verifyTristateValue(this.indeterminateCounterSold);}
verifyTristateValue(numberOfClicks: number)
this.elem.nativeElement.indeterminate = true; // try version 1a
this.issold.nativeElement.indeterminate = true; // try version 1b
}
- 使用(更改)功能
参考:css-tricks
onCheckboxIssoldChange(checkbox: any) {
if (checkbox.readOnly) {
checkbox.checked = checkbox.readOnly = false;
}
else if (!checkbox.checked) {
checkbox.readOnly = checkbox.indeterminate = true;
}
}
...以及两者的变化。
解决方案
如果您正确应用,第二种方法实际上确实有效。目前我只是在自己身上传递事件,没有抓住复选框。
所以html保持不变,我们确保定义事件的目标
onCheckboxIssoldChange(checkboxEventChange: any) {
var checkbox = checkboxEventChange.target;
if (checkbox.readOnly) {
checkbox.checked = checkbox.readOnly = false;
}
else if (!checkbox.checked) {
checkbox.readOnly = checkbox.indeterminate = true;
}
}
推荐阅读
- android - 反应原生图像调整大小裁剪图像
- python - 列表元素在 0 元素之后等于 0
- python - Python - 从 SQLite 游标实例化对象
- node.js - 通过 nodemailer 使用 webmail 发送电子邮件
- python - Python中的颜色
- reactjs - 无法将 npm 终端设置为 VS 代码/窗口
- javascript - 从 React js 发送一个 blob 视频文件到烧瓶服务器
- laravel - 为什么路线在 laravel-livewire 中不起作用?
- vba - Visio中的形状动画通过VBA
- java - Java CXF / JAX-WS 可以验证入站 XML 字符编码吗?