反转“已检查"mat-checkbox 的值 [英] Invert "checked" value of a mat-checkbox
问题描述
当 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>
或者我需要像这样创建一个自定义指令:
我的目标是这段代码:
this.filterGroup = new FormGroup({已解决:new FormControl(),});this.filterGroup.getRawValue();
当复选框被选中时返回{resolved: false}
.
Tobias,即使您没有输入,formControl 也存在.所以,如果你有
form = new FormGroup({已解决:new FormControl()})
你可以使用类似的东西:
<mat-checkbox [checked]="!form.value.resolved"(change)="form.get('resolved').setValue(!$event.checked)">检查我!</mat-checkbox>
请注意,如果您只有一个唯一的 formControl,则:
mycontrol=new FormControl()
你使用
<mat-checkbox [checked]="!mycontrol.value"(change)="mycontrol.setValue(!$event.checked)">检查我!</mat-checkbox>
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.
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>
这篇关于反转“已检查"mat-checkbox 的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!