2

When a Angular Material mat-checkbox (https://material.angular.io/components/checkbox/overview) is checked it has the value "true". When it is unchecked it has the value "false".

Is there a way to turn this behaviour around? I need just the opposite. A checked checkbox should serialize to "false" and a unchecked one should serialize to "true" when calling this.filterFormGroup.getRawValue().

I was hoping that there is something like this:

<mat-checkbox [myCustomCheckedValue]="false" [myCustomUnCheckedValue]="true"></mat-checkbox>

Or do I need to create a custom directive like so:

<mat-inverted-checkbox></mat-inverted-checkbox>

My goal is that this code:

    this.filterGroup = new FormGroup({
        resolved: new FormControl(),
    });

    this.filterGroup.getRawValue();

returns {resolved: false} when the checkbox is checked.

tobias47n9e
  • 2,233
  • 3
  • 28
  • 54

4 Answers4

4

Tobias, a formControl exists even if you don't have an input. So, if you have

  form = new FormGroup({
    resolved: new FormControl()
  })

you can use something like:

<mat-checkbox [checked]="!form.value.resolved"
              (change)="form.get('resolved').setValue(!$event.checked)">
   Check me!
</mat-checkbox>

see in stackblitz

Note, if you only have a unique formControl then:

mycontrol=new FormControl()

you use

<mat-checkbox [checked]="!mycontrol.value"
              (change)="mycontrol.setValue(!$event.checked)">
   Check me!
</mat-checkbox>
raikumardipak
  • 1,461
  • 2
  • 29
  • 49
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • You don't need to bind `[checked]` (unless you want the initial state checked), but you should set the initial true/unchecked value on the `FormControl`. – G. Tranter Jul 24 '19 at 21:33
2

In case someone wants to do this without a FormControl, the simplest solution is to bind the value input to the checked property:

<mat-checkbox #checkbox [value]="!checkbox.checked">
  {{ checkbox.value }}
</mat-checkbox>
G. Tranter
  • 16,766
  • 1
  • 48
  • 68
0

I used the answer of https://stackoverflow.com/users/8558186/eliseo and made it "false" or "null" for the API:

<mat-checkbox (change)="resolvedFormControl.setValue($event.checked ? false.toString() : null)"
    [checked]="resolvedFormControl.value === false.toString()">
            Resolved
</mat-checkbox>

and in the component:

this.resolvedFormControl = new FormControl(null);
this.resolvedFormControl.setValue(false.toString());

this.filterGroup = new FormGroup({
    resolved: this.resolvedFormControl,
});

this.filterGroup.valueChanges.subscribe(() => {
    console.log(this.filterGroup.getRawValue());
    // resolved is either 'false' or null
}
tobias47n9e
  • 2,233
  • 3
  • 28
  • 54
-1

You can write a custom Pipe to change the received values to the way you want it to be. Like if the received value is true, It will convert the value in the desired way that is false in your case.