在 Angular 复选框上设置不确定

Tay*_*suk 2 checkbox angular

我正在尝试以编程方式将 Angular 复选框的值设置为,false trueindeterminate。我知道我无法将复选框设置为该值,indeterminate但是我们确实可以访问[indeterminate]输入。是否可以通过ngModel某种方式设置所有三个状态?

我有以下代码可以正常工作,但是出现ExpressionChangedAfterItHasBeenCheckedError错误。

HTML

<div *ngFor="let label of ClientLabels | async">
  <label for="{{label.objectId}}">{{label.labelName}}</label>
  <input id="{{label.objectId}}" type="checkbox" name="group" [indeterminate]="checkedLabels()"
      [checked]="checkedLabels(label)" (change)="toggleSelectedLabels(label)" />
</div>
Run Code Online (Sandbox Code Playgroud)

TS

checkedLabels(label): boolean {
    const index = this.selectedLabels.indexOf(label.objectId);
    this. indeterminateState = false;
    if (!this.selectedClients.length) {
      return false;
    }
    if (this.countInArray(this.selectedLabels, label.objectId) === this.selectedClients.length) {
      return true;
    }
    if (index >= 0) {
      this. indeterminateState = true;
    }
  }

countInArray(array, value) {
  return array.reduce((n, x) => n + (x === value), 0);
}
Run Code Online (Sandbox Code Playgroud)

这里的用例类似于 Gmail 中的标签,除了使用客户端代替电子邮件。如果所有电子邮件都具有相同的标签,则它们显示为已检查,但是如果不是所有电子邮件都共享标签,则它将显示不确定,可以在三种状态(真、假、不确定)之间循环。

一季度。我怎样才能像使用 gmail 一样循环浏览这三种状态?

Q2。为什么我得到ExpressionChangedAfterItHasBeenCheckedError当前设置?

这是当前进度的 Stackblitz https://stackblitz.com/edit/angular-3bbutx

Gmail 三态复选框示例

Eli*_*seo 7

要使复选框不确定,您可以使用指令

import { Directive, ElementRef,Input } from '@angular/core';

@Directive({ selector: '[indeterminate]' })
export class IndeterminateDirective {
   @Input() 
   set indeterminate(value)
   {
     this.elem.nativeElement.indeterminate=value;
   }
    constructor(private elem: ElementRef) {
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你的复选框可以像

<input class="pull-left" type="checkbox" 
     [indeterminate]="client.indeterminated" 
     [checked]="client.checked" (click)="click(client)"/>
Run Code Online (Sandbox Code Playgroud)

在哪里

  click(cliente: any) {
    let indeterminated=(!cliente.checked && !cliente.indeterminated) ? true : false;
    let checked=(!cliente.checked && cliente.indeterminated)?true:false
    cliente.indeterminated = indeterminated;
    cliente.checked=checked;
  }
Run Code Online (Sandbox Code Playgroud)

看到你有两个变量“checked”和“indeterminated”,你可以随意循环

  • @Eliseo `&lt;input type="checkbox"&gt;` 已经有一个属性 `indeterminate`,所以如果你删除该指令,它仍然可以正常工作。 (2认同)