Skip to content

Commit 2493797

Browse files
crisbetoandrewseguin
authored andcommitted
fix(select): change event emitted before data binding is updated (#8740)
Fixes the select's `change` event emitting before the `value` binding has been updated, causing consumers that check the data-bound output to get a stale value. Fixes #8739.
1 parent 92d198b commit 2493797

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/lib/select/select.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2371,6 +2371,29 @@ describe('MatSelect', () => {
23712371

23722372
expect(document.activeElement).toBe(select, 'Expected trigger to be focused.');
23732373
}));
2374+
2375+
it('should update the data binding before emitting the change event', fakeAsync(() => {
2376+
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
2377+
const instance = fixture.componentInstance;
2378+
const spy = jasmine.createSpy('change spy');
2379+
2380+
fixture.detectChanges();
2381+
instance.select.change.subscribe(() => spy(instance.selectedFood));
2382+
2383+
expect(instance.selectedFood).toBeFalsy();
2384+
2385+
fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
2386+
fixture.detectChanges();
2387+
flush();
2388+
2389+
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
2390+
fixture.detectChanges();
2391+
flush();
2392+
2393+
expect(instance.selectedFood).toBe('steak-0');
2394+
expect(spy).toHaveBeenCalledWith('steak-0');
2395+
}));
2396+
23742397
});
23752398

23762399
describe('positioning', () => {

src/lib/select/select.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -896,9 +896,9 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit,
896896
}
897897

898898
this._value = valueToEmit;
899+
this.valueChange.emit(valueToEmit);
899900
this._onChange(valueToEmit);
900901
this.selectionChange.emit(new MatSelectChange(this, valueToEmit));
901-
this.valueChange.emit(valueToEmit);
902902
this._changeDetectorRef.markForCheck();
903903
}
904904

0 commit comments

Comments
 (0)