将传入的整数值绑定到表单组中的mat-radio-button值

时间:2019-04-18 16:22:20

标签: angular data-binding radio-button angular-material formgroups

我正在从数据库加载整数类型值以填充表单组的单选按钮。如果我将传入的整数转换为字符串,则收音机组仅读取值。如何使mat-radio-group接受整数值?

我尝试将value="1"更改为[value]="1",但这没有任何效果。我唯一能找到的参考是在material2 github页面here

上的一个问题

HTML

 <form class="mb-4" [formGroup]="wifiForm">
        <label id="wifi_available">Is working WiFi present on the property?</label>
        <mat-radio-group
          aria-labelledby="wifi_available"
          class="list-radio-group w-100 mb-4 mt-2"
          formControlName="wifi_available"
          name="wifi_available"
          fxLayout="column"
          required
        >
          <mat-radio-button class="list-radio-button" color="primary" [value]="1">Yes</mat-radio-button>
          <mat-radio-button class="list-radio-button" color="primary" [value]="2">No</mat-radio-button>
          <mat-error *ngIf="wifiForm.controls.wifi_available.hasError('required').required && wifiForm.controls.wifi_available.touched" class="error"
            >Required field</mat-error
          >
        </mat-radio-group>
...rest of form... 
</form>

组件

ngOnInit() {
    this.wifiForm = this.fb.group({
      wifi_available: ['', Validators.required],
      wifi_deadspots: ['', Validators.required],
      wifi_notes: [''],
    });
    this.orderId = this.route.snapshot.paramMap.get('id');
    this.wifiData = this.route.snapshot.data['order_data']; <== WHERE DATA IS BROUGHT IN
    this.wifiForm.patchValue(this.wifiData); <== WHERE DATA IS PATCHED
  }

来自数据库的值[示例] { wifi_available:1, wifi_deadspots:1, wifi_notes:'熏腊肉...' }

我希望相应地检查mat-radio按钮(如果为1,则选中“是”)。如果我将db字段类型更改为VARCHAR,则按预期检查单选按钮。如果db字段为INT(应为INT),则不会选中任何单选按钮。

1 个答案:

答案 0 :(得分:0)

我添加了

[checked]="wifiForm.value.wifi_available === true"

使用mat-radio-button(wifiForm将1/0视为布尔值),并且有效。

我只需要更新html

<form class="mb-4" [formGroup]="wifiForm">
  <label id="wifi_available">Is working WiFi present on the property?</label>
  <mat-radio-group
          aria-labelledby="wifi_available"
          class="list-radio-group w-100 mb-4 mt-2"
          formControlName="wifi_available"
          name="wifi_available"
          fxLayout="column"
          required
        >
  <mat-radio-button class="list-radio-button" color="primary [checked]="wifiForm.value.wifi_available === true" value="1">Yes</mat-radio-button>
  <mat-radio-button class="list-radio-button" color="primary [checked]="wifiForm.value.wifi_available === false"value="0">No</mat-radio-button>

... </form>

这可以解决我遇到同样问题的其他组件中的其他值。