9
votes

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?

1
Here is stackblitz that shows the problem. I want it to be boolean, not string. stackblitz.com/edit/angular-b1gr7pDave Vronay
Good question. I wonder why so few people are interested in it.Mitulát báti

1 Answers

17
votes

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>