Skip to content

Commit fc15fa2

Browse files
crisbetojosephperrott
authored andcommitted
fix(slide-toggle): not updating model from toggle method (#11846)
1 parent 2330c8b commit fc15fa2

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
@@ -50,7 +50,6 @@ describe('MatSlideToggle without forms', () => {
5050
let labelElement: HTMLLabelElement;
5151
let inputElement: HTMLInputElement;
5252

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

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

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

260-
slideToggle.toggle();
258+
labelElement.click();
261259
fixture.detectChanges();
262-
});
260+
tick();
261+
262+
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({checked: true}));
263+
subscription.unsubscribe();
264+
}));
263265

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

831833
expect(modelInstance.pristine).toBe(true);
832834
}));
835+
836+
it('should set the model value when toggling via the `toggle` method', fakeAsync(() => {
837+
expect(testComponent.modelValue).toBe(false);
838+
839+
fixture.debugElement.query(By.directive(MatSlideToggle)).componentInstance.toggle();
840+
fixture.detectChanges();
841+
flushMicrotasks();
842+
843+
fixture.detectChanges();
844+
expect(testComponent.modelValue).toBe(true);
845+
}));
846+
833847
});
834848

835849
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
@@ -277,6 +277,7 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
277277
/** Toggles the checked state of the slide-toggle. */
278278
toggle(): void {
279279
this.checked = !this.checked;
280+
this.onChange(this.checked);
280281
}
281282

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

0 commit comments

Comments
 (0)