Skip to content

Commit 645e63d

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 391a9fd commit 645e63d

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

src/lib/radio/radio.spec.ts

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

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

src/lib/radio/radio.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -380,14 +380,17 @@ export class MatRadioButton extends _MatRadioButtonMixinBase
380380
get value(): any { return this._value; }
381381
set value(value: any) {
382382
if (this._value !== value) {
383+
const group = this.radioGroup;
383384
this._value = value;
384-
if (this.radioGroup !== null) {
385-
if (!this.checked) {
386-
// Update checked when the value changed to match the radio group's value
387-
this.checked = this.radioGroup.value === value;
388-
}
385+
386+
if (group) {
387+
// Update `checked`, because the button's value might not match up with the group anymore.
388+
this.checked = group.value === value;
389+
389390
if (this.checked) {
390-
this.radioGroup.selected = this;
391+
group.selected = this;
392+
} else if (group.selected === this) {
393+
group.selected = null;
391394
}
392395
}
393396
}

0 commit comments

Comments
 (0)