I had the same problem as OP and I tried both the most popular and second most popular answers but neither of them worked for me. I'm using Angular 10 and this post is 4 years old so I hope this answer will help someone else who has my problem.
I noticed that the mat-radio-button was being assigned a class 'mat-radio-checked'
when you checked it. The reason I believe that the above 2 answers no longer work is that the value of the button is set before you receive it in the ts file so no matter how you try to assign the _checked
value to false
it isn't going to work. But changing that class is doable. This method also allows you to deselect the button without having to keep track of any kind of global variable. Here's a generic example:
In the html assign each button a reference variable using the #
and an on click event passing the event and button reference.
<mat-radio-group class="radio-group">
<mat-radio-button #option1 class="radio-item" value="New User" (click)="onRadioClick($event, option1)”>New User</mat-radio-button>
<mat-radio-button #option2 class="radio-item" value=“Existing User" (click)="onRadioClick($event, option2)”>Existing User</mat-radio-button>
</mat-radio-group>
Then in the onRadioClick
function check to make sure that the button the user clicked has a class 'mat-radio-checked'
; if it does then remove the check class and add our own flag marked-unchecked
. This way if you uncheck an option then check it again we will know that it has been checked again and can go ahead and add the 'mat-radio-checked'
class again.
onRadioClick(event: any, button: any): void {
let targetButton = event.target;
while (targetButton && targetButton.parentNode && targetButton.parentNode.classList) {
targetButton = targetButton.parentNode;
if (targetButton.classList.contains('mat-radio-checked') && !targetButton.classList.contains('marked-unchecked')) {
targetButton.classList.remove('mat-radio-checked');
targetButton.classList.add('marked-unchecked');
break;
}
if (targetButton.classList.contains('marked-unchecked')) {
targetButton.classList.remove('marked-unchecked');
targetButton.classList.add('mat-radio-checked');
}
}
}
For further explanation on this just inspect your mat-radio-button element in your browser and you'll be able to see the mat-radio-checked
css class I was talking about and it should become apparent.