diff --git a/src/material/radio/radio.spec.ts b/src/material/radio/radio.spec.ts index 65f6541115cd..3dcd4312fd73 100644 --- a/src/material/radio/radio.spec.ts +++ b/src/material/radio/radio.spec.ts @@ -345,6 +345,27 @@ describe('MatRadio', () => { expect(radioInstances[2].checked).toBeFalsy('should not select the third button'); }); + it(`should update checked status if changed value to radio group's value`, () => { + groupInstance.value = 'apple'; + radioInstances[0].value = 'apple'; + fixture.detectChanges(); + + expect(groupInstance.selected).toBe( + radioInstances[0], 'expect group selected to be first button'); + expect(radioInstances[0].checked).toBeTruthy('expect group select the first button'); + expect(radioInstances[1].checked).toBeFalsy('should not select the second button'); + expect(radioInstances[2].checked).toBeFalsy('should not select the third button'); + + radioInstances[0].value = 'watermelon'; + fixture.detectChanges(); + + expect(groupInstance.value).toBeFalsy(); + expect(groupInstance.selected).toBeFalsy('expect group selected to be null'); + expect(radioInstances[0].checked).toBeFalsy('should not select the first button'); + expect(radioInstances[1].checked).toBeFalsy('should not select the second button'); + expect(radioInstances[2].checked).toBeFalsy('should not select the third button'); + }); + it('should apply class based on color attribute', () => { expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-accent'))) .toBe(true, 'Expected every radio element to use the accent color by default.'); diff --git a/src/material/radio/radio.ts b/src/material/radio/radio.ts index fc7d93470aeb..50b6e49ce662 100644 --- a/src/material/radio/radio.ts +++ b/src/material/radio/radio.ts @@ -402,14 +402,17 @@ export class MatRadioButton extends _MatRadioButtonMixinBase get value(): any { return this._value; } set value(value: any) { if (this._value !== value) { + const group = this.radioGroup; this._value = value; - if (this.radioGroup !== null) { - if (!this.checked) { - // Update checked when the value changed to match the radio group's value - this.checked = this.radioGroup.value === value; - } + + if (group) { + // Update `checked`, because the button's value might not match up with the group anymore. + this.checked = group.value === value; + if (this.checked) { - this.radioGroup.selected = this; + group.selected = this; + } else if (group.selected === this) { + group.selected = null; } } }