Skip to content

Commit 41aa96b

Browse files
committed
fix(slide-toggle): not updating model from toggle method
Fixes the slide toggle not propagating its value to the `ControlValueAccessor` when its value is changed through the `toggle` method. Fixes #11812.
1 parent f31b2f4 commit 41aa96b

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/lib/slide-toggle/slide-toggle.spec.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ describe('MatSlideToggle without forms', () => {
4949
let labelElement: HTMLLabelElement;
5050
let inputElement: HTMLInputElement;
5151

52-
// This initialization is async() because it needs to wait for ngModel to set the initial value.
5352
beforeEach(fakeAsync(() => {
5453
fixture = TestBed.createComponent(SlideToggleBasic);
5554

@@ -251,14 +250,17 @@ describe('MatSlideToggle without forms', () => {
251250
expect(testComponent.lastEvent.checked).toBe(true);
252251
}));
253252

254-
it('should support subscription on the change observable', () => {
255-
slideToggle.change.subscribe((event: MatSlideToggleChange) => {
256-
expect(event.checked).toBe(true);
257-
});
253+
it('should support subscription on the change observable', fakeAsync(() => {
254+
const spy = jasmine.createSpy('change spy');
255+
const subscription = slideToggle.change.subscribe(spy);
258256

259-
slideToggle.toggle();
257+
labelElement.click();
260258
fixture.detectChanges();
261-
});
259+
tick();
260+
261+
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({checked: true}));
262+
subscription.unsubscribe();
263+
}));
262264

263265
it('should show a ripple when focused by a keyboard action', fakeAsync(() => {
264266
expect(slideToggleElement.querySelectorAll('.mat-ripple-element').length)
@@ -739,6 +741,18 @@ describe('MatSlideToggle with forms', () => {
739741

740742
expect(modelInstance.pristine).toBe(true);
741743
}));
744+
745+
it('should set the model value when toggling via the `toggle` method', fakeAsync(() => {
746+
expect(testComponent.modelValue).toBe(false);
747+
748+
fixture.debugElement.query(By.directive(MatSlideToggle)).componentInstance.toggle();
749+
fixture.detectChanges();
750+
flushMicrotasks();
751+
752+
fixture.detectChanges();
753+
expect(testComponent.modelValue).toBe(true);
754+
}));
755+
742756
});
743757

744758
describe('with a FormControl', () => {

src/lib/slide-toggle/slide-toggle.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
252252
/** Toggles the checked state of the slide-toggle. */
253253
toggle(): void {
254254
this.checked = !this.checked;
255+
this.onChange(this.checked);
255256
}
256257

257258
/** Function is called whenever the focus changes for the input element. */

0 commit comments

Comments
 (0)