Angular material mat-radio-group doesn´t allow default value with ngModel

Viewed 628

I am currently struggling with a more complex implementation using mat-radio-group. I upgraded my Angular version from 10 to 13 and now a default value in a mat-radio-group is not recognized anymore.

To keep it simple you can reproduce it with the example from Angular Material: https://material.angular.io/components/radio/examples

Use the stackblitz of "Radios with ngModel". Unfortunately I couldn´t fork it. Then try to set "Winter" as default. It won´t be checked after recompiling.

Is the only way to get around this by using the [checked] property? What did Angular change to change this behavior?

1 Answers

The checked attribute for setting the default radio button has been there all the time, from my recollection at least since Material 9.x (and possibly before).

Can you try the following:

In you TS code:

Set your favorite season selection to a constant string value:

favoriteSeason: string = 'Spring';

Then in your HTML set the checked attribute in the ngFor loop for each mat-radio-button control as follows:

[checked]="favoriteSeason == season"

So, your radio group will look as shown:

<mat-radio-group
      aria-labelledby="example-radio-group-label"
      class="example-radio-group"
      [(ngModel)]="favoriteSeason">
    <mat-radio-button
        class="example-radio-button"
        *ngFor="let season of seasons"
        [value]="season"
        [checked]="favoriteSeason == season">
        {{ season }}
    </mat-radio-button>
</mat-radio-group>

The above should give you the desired default selection.

Edit: You might have experimented with the above and found out that the checked condition isn't needed if we set the initial value in our TS code.

Try the following:

In your TS code, don't assign the binding variable. Leave it like this:

favoriteSeason: string;

Next, add the following HTML button:

<button (click)="setValue()">Press Here</button>

Now, define the button click event setValue as shown:

setValue() {
    this.favoriteSeason = 'Autumn';
}

When the above runs, there is no initial selection. When you click on the button the season will be set to 'Autumn'!

The above shows that you can set the default radio selection using either code or with the checked attribute.

Related