当选中 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/