mdailey77
mdailey77

Reputation: 2409

pre-selecting material radio button using reactive forms not working

I have an Angular Material radio button group containing two radio buttons. I'm using Reactive Forms and want to pre-select the first radio button which has a value of 'true'.

I initialize the value of the associated FormControl as part of a FormGroup like so:

userFormGroup = new FormGroup({
  orgType: new FormControl(true),
  ...
})

I verified the value is set to true by adding this code beneath the radio group: <p>orgTypeBool value: {{userFormGroup.get('orgType').value}}</p>. The value does return 'true'.

I tried pre-selecting the first radio button by using the selected Input decorator as mentioned in the material radio button documentation: https://material.angular.io/components/radio/api#MatRadioGroup. When I try it out I get the following error: TypeError: Cannot create property 'checked' on boolean 'true'.

Here is my code:

<mat-radio-group formControlName="orgTypeBool" [selected]="userFormGroup.get('orgType').value" (change)="controlChange()">
    <mat-radio-button id="nonprofit" value="true">Non-Profit</mat-radio-button>
    <mat-radio-button id="commerical" value="false">Commerical</mat-radio-button>
</mat-radio-group>
<p>orgTypeBool value: {{userFormGroup.get('orgType').value}}</p>

I think there's a way to do it using [selected] but I don't know what the right syntax would be. How would I pre-select the first radio button based on the FormControl's value?

Upvotes: 0

Views: 1223

Answers (2)

yarozar
yarozar

Reputation: 11

In template: value="true" - string 'true', while in component: new FormControl(true) - boolean true. They are not equal thus radio button is not pre-selected.

Upvotes: 1

mdailey77
mdailey77

Reputation: 2409

I found a solution. Not sure if it's best practice.

I added a checked Input decorator to the first radio button and set it to 'true'.

<mat-radio-group formControlName="orgTypeBool" (change)="controlChange()">
    <mat-radio-button id="nonprofit" value="true" [checked]="true">Non-Profit</mat-radio-button>
    <mat-radio-button id="commerical" value="false">Commerical</mat-radio-button>
</mat-radio-group>

Upvotes: 0

Related Questions