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>
selectedValue: boolean | null = null;
selected = false;
toggleSelection() {
this.selected = !this.selected;
this.selectedValue = this.selected ? true : null; // Toggle selection
between true and null
}
html
<mat-radio-group [(ngModel)]="selectedValue">
<mat-radio-button [value]="true" [checked]="selected">
{{ selected ? 'Selected' : 'Not Selected' }}
</mat-radio-button>
</mat-radio-group>
<button (click)="toggleSelection()">
Toggle selection
</button>
New contributor
Jawad Mehmood is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.