Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to bind mat-radio-group to nullable boolean?

I have a simple form showing data from a REST server. One of the fields is a boolean but can be null. My UI has a mat-radio-group with two mat-radio-button elements, one with value "true" and one with value "false". I would expect that if it was null, neither would be on, and clicking one would set the value to true or false. However, it doesn't do anything at all.

I tried using ng-value instead of value, but that didn't have any effect.

      <mat-radio-group [(ngModel)]="canBeTrueFalseOrNull">
        <mat-radio-button value="true">yes</mat-radio-button>
        <mat-radio-button value="false">no</mat-radio-button>
      </mat-radio-group>

I supposed a can transform the data from the server into strings and then change it back again when I update it, but that seems overly complex. Is there an easier way to do this?

like image 463
Dave Vronay Avatar asked Aug 24 '19 02:08

Dave Vronay


1 Answers

To assign a boolean value to each radio button, you should bind the value using the brackets syntax:

[value]="true"

Without the brackets, the value is the string "true". The following code snippet should work, as shown in this stackblitz:

<mat-radio-group [(ngModel)]="canBeTrueFalseOrNull">
  <mat-radio-button [value]="true">yes</mat-radio-button>
  <mat-radio-button [value]="false">no</mat-radio-button>
</mat-radio-group>
like image 128
ConnorsFan Avatar answered Sep 25 '22 09:09

ConnorsFan