gpt4 book ai didi

angular - 反转 mat-checkbox 的 "checked"值

转载 作者:行者123 更新时间:2023-12-02 19:55:30 24 4
gpt4 key购买 nike

当选中 Angular Material mat-checkbox ( https://material.angular.io/components/checkbox/overview ) 时,它的值为“true”。当未选中时,其值为“false”。

有办法扭转这种行为吗?我需要的恰恰相反。调用 this.filterFormGroup.getRawValue() 时,选中的复选框应序列化为“false”,未选中的复选框应序列化为“true”。

我希望有这样的事情:

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

或者我是否需要创建一个像这样的自定义指令:

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

我的目标是这段代码:

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

this.filterGroup.getRawValue();

当复选框被选中时,返回{resolved: false}

最佳答案

Tobias,即使您没有输入,formControl 也存在。所以,如果你有

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

你可以使用类似的东西:

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

参见 stackblitz

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

mycontrol=new FormControl()

你使用

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

关于angular - 反转 mat-checkbox 的 "checked"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com