代码之家  ›  专栏  ›  技术社区  ›  qqtf

angular2+:如何循环遍历三状态(不确定)复选框的值

  •  0
  • qqtf  · 技术社区  · 5 年前

    我使用angular 2+,bootstrap4,不使用jQuery


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

    • 正确:所有售出的商品
    • 错误:所有未售出的商品
    • null:不要使用此条件进行筛选

    我成功地将“不确定”作为复选框的初始值初始化:

    • html。组成部分:
    <input class="form-control" type="checkbox" formControlName="issold" (change)="onCheckboxIssoldChange($event)"
                                                       [indeterminate]="true" #issold>
    
    • ts组件
    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;
    }
    }
    

    ... 两者都有变化。

    0 回复  |  直到 5 年前
        1
  •  0
  •   qqtf    5 年前

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

    因此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;
    }
    }