【发布时间】:2021-06-07 16:33:11
【问题描述】:
我使用 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;
}
}
...以及两者的变体。
【问题讨论】:
-
只是为了明确你的目标是有一个具有三种状态的复选框:真、假和未触及?即一旦用户点击了复选框,他们将只能在两种状态之间切换,但您不希望“未触及”状态被视为真或假?
-
不,这正是问题所在。这就是我现在所拥有的。一旦用户开始点击,他应该能够回到不确定状态(你知道,在视觉上,在框中的细垂直线)。否则,一旦他单击了先前查询中的框,他/她将不得不重新加载页面以进行他/她不希望使用此标准的后续查询。它实际上只是几个复选框,在输入字段旁边,以更大的形式。