Issue
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?
Solution
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>
Answered By - mdailey77
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.