反转“已检查"垫复选框的值 [英] Invert "checked" value of a mat-checkbox

查看:100
本文介绍了反转“已检查"垫复选框的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当角度材料mat-checkbox( https://material.angular.io/components/checkbox/overview )被选中,其值为"true".取消选中时,其值为"false".

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".

有没有办法解决此问题?我只需要相反.调用this.filterFormGroup.getRawValue()时,选中的复选框应序列化为"false",而未选中的复选框应序列化为"true".

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().

我希望有这样的东西:

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

我的目标是该代码:

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

    this.filterGroup.getRawValue();

选中该复选框后,

返回{resolved: false}.

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

推荐答案

Tobias,即使没有输入,formForm也会存在.所以,如果你有

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

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

您可以使用以下内容:

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

请参见 stackblitz

see in stackblitz

注意,如果只有唯一的formControl,则:

Note, if you only have a unique formControl then:

mycontrol=new FormControl()

您使用

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

这篇关于反转“已检查"垫复选框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆