首页 > 解决方案 > angular2+:如何遍历三态(不确定)复选框的值

问题描述

我使用 Angular 2+,bootstrap4,没有 jQuery


复选框需要具有三种状态的原因是因为我们使用它在后端执行查询(作为多个条件之一),如下所示:


我设法用不确定的初始值初始化复选框:

<input class="form-control" type="checkbox" formControlName="issold" (change)="onCheckboxIssoldChange($event)"
                                                   [indeterminate]="true" #issold>
set indeterminate(value: boolean) {
        this.elem.nativeElement.indeterminate = value;
    }

为了遍历这些值,我尝试了两种方法:

  1. 使用 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
    }
  1. 使用(更改)功能

参考:css-tricks

onCheckboxIssoldChange(checkbox: any) {
  if (checkbox.readOnly) {
  checkbox.checked = checkbox.readOnly = false;
}
else if (!checkbox.checked) {
  checkbox.readOnly = checkbox.indeterminate = true;
}
}

...以及两者的变化。

标签: angularcheckbox

解决方案


如果您正确应用,第二种方法实际上确实有效。目前我只是在自己身上传递事件,没有抓住复选框。

所以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;
}
}

推荐阅读