Niranjan
Niranjan

Reputation: 587

How to add third state to checkbox?

Hi I am developing web application in angular. I am displaying checkbox with three states. I am distinguishing states usng css classes. The three states are cross-marked,check marked and blank. Below is the implementation part.

<div *ngIf="node.data.checked==true && node.data.allow==true">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate" [checked]="node.data.checked">
        <span class="checkmark"></span>
        {{ node.data.name }}
    </label>
</div>

<div *ngIf="node.data.checked==true && node.data.allow==false">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate" [checked]="node.data.checked">
        <span class="checkmark xmark"></span>
        {{ node.data.name }}

    </label>
</div>

<div *ngIf="node.data.checked==false">
    <label class="container">
        <input (change)="check(node, !node.data.checked)" type="checkbox" [indeterminate]="node.data.indeterminate">
        <span class="checkmark"></span>
        {{ node.data.name }}

    </label>
</div>

I am attaching UI image above. Tri state checbox

Device model1 contains cross marked,device model2 contains check marked and devicemodel4 contains blank. These are three states. Now when user clicks on any one of the checkboxe's state should change in the below path.

blank --> checked --> cross --> blank

Above is circular path. For example, if the checkbox is checked then when the user clicks on it then checkbox should become cross and if the user clicks it again then blank and if the user clicks it again then again checked and so on. Displaying part i have done. Can someone help me to make this work as i said above? Any help would be appreciated. Thank you.

Upvotes: 1

Views: 667

Answers (1)

user184994
user184994

Reputation: 18271

You can use the checkbox indeterminate state for this.

If you bind to the change event, you can pass the checkbox, like so

<input type="checkbox" (change)="toggle($event.target)" />

You can then create the toggle function, like in the link above:

toggle(cb) {
  if (cb.readOnly) cb.checked = cb.readOnly = false;
  else if (!cb.checked) cb.readOnly = cb.indeterminate = true;
}

Here is a StackBlitz demo

Upvotes: 2

Related Questions