[英]Invert “checked” value of a mat-checkbox
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>
还是我需要像这样创建一个自定义指令:
<mat-inverted-checkbox></mat-inverted-checkbox>
我的目标是该代码:
this.filterGroup = new FormGroup({
resolved: new FormControl(),
});
this.filterGroup.getRawValue();
选中此复选框时,返回{resolved: false}
。
如果有人想在没有FormControl的情况下执行此操作,最简单的解决方案是将输入的value
绑定到checked
属性:
<mat-checkbox #checkbox [value]="!checkbox.checked">
{{ checkbox.value }}
</mat-checkbox>
Tobias,即使您没有输入,formForm也存在。 所以,如果你有
form = new FormGroup({
resolved: new FormControl()
})
您可以使用类似:
<mat-checkbox [checked]="!form.value.resolved"
(change)="form.get('resolved').setValue(!$event.checked)">
Check me!
</mat-checkbox>
请注意,如果只有唯一的formControl,则:
mycontrol=new FormControl()
你用
<mat-checkbox [checked]="!mycontrol.value"
(change)="mycontrol.setValue(!$event.checked)">
Check me!
</mat-checkbox>
我使用了https://stackoverflow.com/users/8558186/eliseo的答案,并将API设置为“ false”或“ null”:
<mat-checkbox (change)="resolvedFormControl.setValue($event.checked ? false.toString() : null)"
[checked]="resolvedFormControl.value === false.toString()">
Resolved
</mat-checkbox>
并在组件中:
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
}
您可以编写自定义管道,以将接收到的值更改为所需的方式。 就像接收到的值为true一样,它将以所需的方式转换该值(在您的情况下为false)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.