Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5, Angular Material Checkbox with 3 states (checked, unchecked, indeterminate)

I'm new to Angular and Angular Material, now I'm working as a support in some project. There's a grid with filters and one checkbox, which checks if user in grid is active, inactive, or not chosen. It would be simpler with only two options (active, inactive) but well, I have to make 3 states for it:

  1. 1st click - Checked for active
  2. 2nd click - Unchecked for inactive
  3. 3rd click - Indeterminate for not chosen

Here is checkbox example from official Angular Material documentation: https://stackblitz.com/angular/rxdmnbxmkgk?file=app%2Fcheckbox-configurable-example.html

How to make it in the most simply way?

like image 970
TomasThall Avatar asked Mar 15 '18 09:03

TomasThall


3 Answers

@angular/material >= 9

Here is a ready-to-use component:

import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { MatCheckboxDefaultOptions, MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox';

@Component({
  selector: 'app-tri-state-checkbox',
  templateUrl: './tri-state-checkbox.component.html',
  styleUrls: ['./tri-state-checkbox.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TriStateCheckboxComponent),
      multi: true,
    },
    { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions },
  ],
})
export class TriStateCheckboxComponent implements ControlValueAccessor {

  @Input() tape = [null, true, false];

  value: any;

  disabled: boolean;

  private onChange: (val: boolean) => void;
  private onTouched: () => void;

  writeValue(value: any) {
    this.value = value || this.tape[0];
  }

  setDisabledState(disabled: boolean) {
    this.disabled = disabled;
  }

  next() {
    this.onChange(this.value = this.tape[(this.tape.indexOf(this.value) + 1) % this.tape.length]);
    this.onTouched();
  }

  registerOnChange(fn: any) {
    this.onChange = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouched = fn;
  }

}

and template:

<mat-checkbox [ngModel]="value" (click)="next()" [disabled]="disabled" [indeterminate]="value === false" [color]="value === false ? 'warn' : 'accent'">
  <ng-content></ng-content>
</mat-checkbox>

Usage:

<app-tri-state-checkbox [(ngModel)]="done">is done</app-tri-state-checkbox>
<app-tri-state-checkbox formControlName="done">is done</app-tri-state-checkbox>

You can also override default tape to e.g. enum values:

<app-tri-state-checkbox [tape]="customTape" [(ngModel)]="done">is done</app-tri-state-checkbox>

where customTape replaces default values [null, true, false]

customTape = [Status.open, Status.complete, Status.cancelled];

@angular/material <= 8

Just change

{ provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { clickAction: 'noop' } as MatCheckboxDefaultOptions },

to the deprecated since version 9 MAT_CHECKBOX_CLICK_ACTION

{ provide: MAT_CHECKBOX_CLICK_ACTION, useValue: 'noop' },
like image 95
smnbbrv Avatar answered Oct 08 '22 08:10

smnbbrv


I wanted a solution for this without requiring another component and in a reactive form and this does seem to do the trick, although there is a duplicated animation in one transition:

component.ts

  onChangeCheckbox(checkbox: MatCheckbox): void {
    if (checkbox.indeterminate){
      checkbox.indeterminate = false;
      checkbox.checked = true;
    } 
    // by the time you click it is changed
    else if (!checkbox.indeterminate && !checkbox.checked ){
      checkbox.checked = false;
    }else if (!checkbox.indeterminate && checkbox.checked ){
      checkbox.indeterminate = true;
    }
  }

component.html

<mat-checkbox
                        #checkboxName
                        formControlName="checkboxName"
                        indeterminate="true"
                        (change)="onChangeCheckbox(checkboxName)"
                        id="edit:checkboxName"> 
                        Checkbox Name
                    </mat-checkbox>
like image 37
nck Avatar answered Oct 08 '22 08:10

nck


I tried to reply this Answer but I don't have enough reputation. First thank you for the answer and deep explanation. I was having trouble with the edition of the checkboxes and I figured out that if the value is false this line

this.value = value || this.tape[0];

doesn't work and the color is not updated either. I changed it for this one

this.value = value !== null ? value : this.tape[0];

I hope this comment help others.

like image 2
Julieta Corvi Avatar answered Oct 08 '22 08:10

Julieta Corvi