Skip to content

Commit

Permalink
fix(select): emitting change event twice for reset values
Browse files Browse the repository at this point in the history
Fixes `mat-select` emitting its change event twice when a reset value is selected, as well as when it's selected twice in a row. This PR covers #10859 which would've introduced another issue.

Fixes #10675.
Fixes #13579.
  • Loading branch information
crisbeto committed Dec 29, 2019
1 parent a30094b commit 863b61c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
57 changes: 57 additions & 0 deletions src/material/select/select.spec.ts
Expand Up @@ -3151,6 +3151,63 @@ describe('MatSelect', () => {
.toBeFalsy('Expected no value after tabbing away.');
}));

it('should emit once when a reset value is selected', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const instance = fixture.componentInstance;
const spy = jasmine.createSpy('change spy');

instance.selectedFood = 'sandwich-2';
instance.foods[0].value = null;
fixture.detectChanges();

const subscription = instance.select.selectionChange.subscribe(spy);

fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();

(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();

expect(spy).toHaveBeenCalledTimes(1);

subscription.unsubscribe();
}));

it('should not emit the change event multiple times when a reset option is ' +
'selected twice in a row', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const instance = fixture.componentInstance;
const spy = jasmine.createSpy('change spy');

instance.foods[0].value = null;
fixture.detectChanges();

const subscription = instance.select.selectionChange.subscribe(spy);

fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();

(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();

expect(spy).not.toHaveBeenCalled();

fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();

(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();

expect(spy).not.toHaveBeenCalled();

subscription.unsubscribe();
}));

});

Expand Down
5 changes: 4 additions & 1 deletion src/material/select/select.ts
Expand Up @@ -966,7 +966,10 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit,
if (option.value == null && !this._multiple) {
option.deselect();
this._selectionModel.clear();
this._propagateChanges(option.value);

if (this.value != null) {
this._propagateChanges(option.value);
}
} else {
if (wasSelected !== option.selected) {
option.selected ? this._selectionModel.select(option) :
Expand Down

0 comments on commit 863b61c

Please sign in to comment.