From c1086074ba3a45e4df0a2040ba8e68946dbec3f4 Mon Sep 17 00:00:00 2001 From: tinayuangao Date: Mon, 31 Oct 2016 18:38:58 -0700 Subject: [PATCH] fix(radio): Uncheck radio group if uncheck radio button programmatically (#1561) * added test cases for uncheck * notify all radio buttons after status change and radio group value change to avoid notify radio group twice Fixes #609 --- src/lib/radio/radio.spec.ts | 38 +++++++++++++++++++++++++++++++++++++ src/lib/radio/radio.ts | 14 +++++++++----- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/lib/radio/radio.spec.ts b/src/lib/radio/radio.spec.ts index e47ddcac49f8..361854ddae93 100644 --- a/src/lib/radio/radio.spec.ts +++ b/src/lib/radio/radio.spec.ts @@ -233,6 +233,44 @@ describe('MdRadio', () => { .toBe(0, 'Expect no [md-ripple] in radio buttons'); } })); + + it('should update the group\'s selected radio to null when unchecking that radio ' + + 'programmatically', () => { + let changeSpy = jasmine.createSpy('radio-group change listener'); + groupInstance.change.subscribe(changeSpy); + radioInstances[0].checked = true; + + fixture.detectChanges(); + + expect(changeSpy).toHaveBeenCalled(); + expect(groupInstance.value).toBeTruthy(); + + radioInstances[0].checked = false; + + fixture.detectChanges(); + + expect(changeSpy).toHaveBeenCalledTimes(2); + expect(groupInstance.value).toBeFalsy(); + expect(radioInstances.every(radio => !radio.checked)).toBe(true); + expect(groupInstance.selected).toBeNull(); + }); + + it('should fire a change event from the group whenever a radio checked state changes', () => { + let changeSpy = jasmine.createSpy('radio-group change listener'); + groupInstance.change.subscribe(changeSpy); + radioInstances[0].checked = true; + + fixture.detectChanges(); + + expect(changeSpy).toHaveBeenCalled(); + expect(groupInstance.value).toBeTruthy(); + + radioInstances[1].checked = true; + + fixture.detectChanges(); + + expect(changeSpy).toHaveBeenCalledTimes(2); + }); }); describe('group with ngModel', () => { diff --git a/src/lib/radio/radio.ts b/src/lib/radio/radio.ts index 740eba45e7b5..f272a8a82a2b 100644 --- a/src/lib/radio/radio.ts +++ b/src/lib/radio/radio.ts @@ -306,15 +306,19 @@ export class MdRadioButton implements OnInit { } set checked(newCheckedState: boolean) { - if (newCheckedState) { - // Notify all radio buttons with the same name to un-check. - this.radioDispatcher.notify(this.id, this.name); - } - this._checked = newCheckedState; if (newCheckedState && this.radioGroup && this.radioGroup.value != this.value) { this.radioGroup.selected = this; + } else if (!newCheckedState && this.radioGroup && this.radioGroup.value == this.value) { + // When unchecking the selected radio button, update the selected radio + // property on the group. + this.radioGroup.selected = null; + } + + if (newCheckedState) { + // Notify all radio buttons with the same name to un-check. + this.radioDispatcher.notify(this.id, this.name); } }