我使用angular 2+,bootstrap4,不使用jQuery
复选框需要有三种状态的原因是,我们使用它在后端执行查询(作为许多条件之一),如下所示:
-
正确:所有售出的商品
-
错误:所有未售出的商品
-
null:不要使用此条件进行筛选
我成功地将“不确定”作为复选框的初始值初始化:
<input class="form-control" type="checkbox" formControlName="issold" (change)="onCheckboxIssoldChange($event)"
[indeterminate]="true" #issold>
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;
}
}
... 两者都有变化。