Invert “checked” value of a mat-checkbox

你说的曾经没有我的故事 提交于 2019-12-13 20:24:29

问题


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.


回答1:


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>



回答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>



回答3:


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
}



回答4:


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.



来源:https://stackoverflow.com/questions/57185576/invert-checked-value-of-a-mat-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!