Angular Material Radio buttons - default selection

28 Views Asked by At

I want to set a default selection for a radio group

In my html file I have

    <mat-radio-group [(ngModel)]="selectedId">
        <mat-radio-button [value]="-1" [checked]="selectedId === -1"
            ><span i18n="@@keep-origin">Keep origin</span>
        </mat-radio-button>
        @for (info of data; track info.id) {
            <mat-radio-button [value]="info.id">{{ info.label }}</mat-radio-button>
        }
    </mat-radio-group>
        <pre>{{ selectedId }}</pre>

And in my ts file I have

export interface DataDto {
    label: string;
    id: string;
}
...
    selectedId = -1;

I would expect to have the first option selected - since it has the value -1. I would have expected that checked is not required since its handled via the ngModel. Additionally the <pre> Tag displays when I select the second option info.id instead of the value of the id.

Using Angular Material 17.

1

There are 1 best solutions below

1
Naren Murali On BEST ANSWER

Your code does not have any issues, please check the below working example! please share back the stackblitz with the issue replicated if the issue persists!

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatRadioModule } from '@angular/material/radio';
export interface DataDto {
  label: string;
  id: string;
}
/**
 * @title Basic radios
 */
@Component({
  selector: 'radio-overview-example',
  template: `
  <mat-radio-group [(ngModel)]="selectedId">
    <mat-radio-button [value]="-1"
      ><span i18n="@@keep-origin">Keep origin</span>
    </mat-radio-button>
    @for (info of data; track info.id) {
    <mat-radio-button [value]="info.id">{{ info.label }}</mat-radio-button>
    }
  </mat-radio-group>
  <pre>{{ selectedId }}</pre>

  `,
  styleUrl: 'radio-overview-example.css',
  standalone: true,
  imports: [MatRadioModule, FormsModule],
})
export class RadioOverviewExample {
  selectedId = -1;
  data: DataDto[] = [
    { id: '1', label: 'one' },
    { id: '2', label: 'two' },
    { id: '3', label: 'three' },
  ];
}

Stackblitz Demo