Skip to content

Commit 5a29a88

Browse files
committed
fix(radio): deselect button if value doesn't match up with the group anymore
Handles the case where a radio button is selected and then its value is changed to something that doesn't match up with the group anymore.
1 parent 6a7fc81 commit 5a29a88

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

src/material/radio/radio.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,27 @@ describe('MatRadio', () => {
345345
expect(radioInstances[2].checked).toBeFalsy('should not select the third button');
346346
});
347347

348+
it(`should update checked status if changed value to radio group's value`, () => {
349+
groupInstance.value = 'apple';
350+
radioInstances[0].value = 'apple';
351+
fixture.detectChanges();
352+
353+
expect(groupInstance.selected).toBe(
354+
radioInstances[0], 'expect group selected to be first button');
355+
expect(radioInstances[0].checked).toBeTruthy('expect group select the first button');
356+
expect(radioInstances[1].checked).toBeFalsy('should not select the second button');
357+
expect(radioInstances[2].checked).toBeFalsy('should not select the third button');
358+
359+
radioInstances[0].value = 'watermelon';
360+
fixture.detectChanges();
361+
362+
expect(groupInstance.value).toBeFalsy();
363+
expect(groupInstance.selected).toBeFalsy('expect group selected to be null');
364+
expect(radioInstances[0].checked).toBeFalsy('should not select the first button');
365+
expect(radioInstances[1].checked).toBeFalsy('should not select the second button');
366+
expect(radioInstances[2].checked).toBeFalsy('should not select the third button');
367+
});
368+
348369
it('should apply class based on color attribute', () => {
349370
expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-accent')))
350371
.toBe(true, 'Expected every radio element to use the accent color by default.');

src/material/radio/radio.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -402,14 +402,17 @@ export class MatRadioButton extends _MatRadioButtonMixinBase
402402
get value(): any { return this._value; }
403403
set value(value: any) {
404404
if (this._value !== value) {
405+
const group = this.radioGroup;
405406
this._value = value;
406-
if (this.radioGroup !== null) {
407-
if (!this.checked) {
408-
// Update checked when the value changed to match the radio group's value
409-
this.checked = this.radioGroup.value === value;
410-
}
407+
408+
if (group) {
409+
// Update `checked`, because the button's value might not match up with the group anymore.
410+
this.checked = group.value === value;
411+
411412
if (this.checked) {
412-
this.radioGroup.selected = this;
413+
group.selected = this;
414+
} else if (group.selected === this) {
415+
group.selected = null;
413416
}
414417
}
415418
}

0 commit comments

Comments
 (0)