Skip to content

Commit

Permalink
fix(slide-toggle): report change to model before firing a change event (
Browse files Browse the repository at this point in the history
#7076)

Whenever the value of the slide-toggle changes through interaction, a `change` event will be emitted. The value change then will be reported to the `ControlValueAccessor` which fires the `ngModelChange` output.

Right now the `ngModelChange` output fires after the normal `change` output. This should be the other way around because developers expect the two-way data binding to already reflect the change.

Fixes #7074
  • Loading branch information
devversion authored and andrewseguin committed Sep 29, 2017
1 parent 504ba70 commit c82fca8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
29 changes: 28 additions & 1 deletion src/lib/slide-toggle/slide-toggle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,8 @@ describe('MatSlideToggle with forms', () => {
declarations: [
SlideToggleWithForm,
SlideToggleWithModel,
SlideToggleWithFormControl
SlideToggleWithFormControl,
SlideToggleWithModelAndChangeEvent,
]
});

Expand Down Expand Up @@ -795,6 +796,24 @@ describe('MatSlideToggle with forms', () => {
expect(testComponent.isSubmitted).toBe(true);
});
});

describe('with model and change event', () => {
it('should report changes to NgModel before emitting change event', () => {
const fixture = TestBed.createComponent(SlideToggleWithModelAndChangeEvent);
fixture.detectChanges();

const labelEl = fixture.debugElement.query(By.css('label')).nativeElement;

spyOn(fixture.componentInstance, 'onChange').and.callFake(() => {
expect(fixture.componentInstance.checked)
.toBe(true, 'Expected the model value to have changed before the change event fired.');
});

labelEl.click();

expect(fixture.componentInstance.onChange).toHaveBeenCalledTimes(1);
});
});
});

@Component({
Expand Down Expand Up @@ -873,3 +892,11 @@ class SlideToggleWithTabindexAttr {}
class SlideToggleWithoutLabel {
label: string;
}

@Component({
template: `<md-slide-toggle [(ngModel)]="checked" (change)="onChange()"></md-slide-toggle>`
})
class SlideToggleWithModelAndChangeEvent {
checked: boolean;
onChange: () => void = () => {};
}
2 changes: 1 addition & 1 deletion src/lib/slide-toggle/slide-toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ export class MatSlideToggle extends _MatSlideToggleMixinBase implements OnDestro
let event = new MatSlideToggleChange();
event.source = this;
event.checked = this.checked;
this.change.emit(event);
this.onChange(this.checked);
this.change.emit(event);
}

_onDragStart() {
Expand Down

0 comments on commit c82fca8

Please sign in to comment.