angularangular-material

Dynamically select radio button in angular


I am trying to select radio buttons dynamically. Below is the code and stackblitz link. Unfortunately the button is always selected/checked. How can I toggle the radio button selection on the toggle button click.

example.component.ts

selected = false;

toggleSelection() {
    this.selected = !this.selected;
  }

example.component.html

<mat-radio-group [(ngModel)]="selected">
  <mat-radio-button [value]="selected" [checked]="selected">
    {{ selected }}
  </mat-radio-button>
</mat-radio-group>

    <button
        (click)="toggleSelection()"
      >
        Toggle selection
      </button>

Solution

  • The problem is that you assign the [value]="selected" to the <mat-adio-button>.

    Instead, you should assign [value]="true". Meanwhile, you don't need [checked] attribute as you apply the [(ngModel)] in <mat-radio-group>.

    <mat-radio-group [(ngModel)]="selected">
      <mat-radio-button [value]="true">
        {{ selected }}
      </mat-radio-button>
    </mat-radio-group>
    

    Demo @ StackBlitz