Skip to content

Commit 4102f25

Browse files
committed
fix(slide-toggle): not updating model or dispatching change event from toggle method
Fixes the slide toggle not propagating its value to the `ControlValueAccessor` or dispatching its change event when its value is changed through the `toggle` method. It seems like we had a test for one of these cases, but it wasn't failing when it was supposed to. Fixes #11812.
1 parent f31b2f4 commit 4102f25

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

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

Lines changed: 17 additions & 4 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

@@ -252,12 +251,14 @@ describe('MatSlideToggle without forms', () => {
252251
}));
253252

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

259257
slideToggle.toggle();
260258
fixture.detectChanges();
259+
260+
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({checked: true}));
261+
subscription.unsubscribe();
261262
});
262263

263264
it('should show a ripple when focused by a keyboard action', fakeAsync(() => {
@@ -739,6 +740,18 @@ describe('MatSlideToggle with forms', () => {
739740

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

744757
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._emitChangeEvent();
255256
}
256257

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

0 commit comments

Comments
 (0)