Skip to content

Commit

Permalink
fix(radio): deselect button if value doesn't match up with the group …
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
crisbeto committed Jun 20, 2019
1 parent 6a7fc81 commit 5a29a88
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
21 changes: 21 additions & 0 deletions src/material/radio/radio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand Down
15 changes: 9 additions & 6 deletions src/material/radio/radio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
Expand Down

0 comments on commit 5a29a88

Please sign in to comment.