Skip to content

Commit

Permalink
fix(radio): Uncheck radio group if uncheck radio button programmatica…
Browse files Browse the repository at this point in the history
…lly (#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
  • Loading branch information
tinayuangao authored and hansl committed Nov 1, 2016
1 parent 92ac392 commit c108607
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
38 changes: 38 additions & 0 deletions src/lib/radio/radio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
14 changes: 9 additions & 5 deletions src/lib/radio/radio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down

0 comments on commit c108607

Please sign in to comment.