2

当检查角材料mat-checkboxhttps://material.angular.io/components/checkbox/overview)时,它具有“ true”的值。未选中时,它的值为“false”。

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

我希望有这样的事情:

<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}选中复选框时返回。

4

4 回答 4

3

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>
于 2019-07-24T18:49:52.990 回答
2

如果有人想在没有 FormControl 的情况下执行此操作,最简单的解决方案是将value输入绑定到checked属性:

<mat-checkbox #checkbox [value]="!checkbox.checked">
  {{ checkbox.value }}
</mat-checkbox>
于 2019-07-24T21:10:19.283 回答
0

我使用了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
}
于 2019-07-25T07:17:41.850 回答
-1

您可以编写自定义管道以将接收到的值更改为您想要的方式。就像接收到的值为真一样,它会以在您的情况下为假的所需方式转换值。

于 2019-07-24T14:49:56.737 回答