Skip to content

Commit

Permalink
fix(select): component value not in sync with control value on init (#…
Browse files Browse the repository at this point in the history
…18443)

Fixes the `MatSelect.value` property not being in sync with the `ControlValueAccessor` initial value on init.

Fixes #18423.

(cherry picked from commit 99c6112)
  • Loading branch information
crisbeto authored and andrewseguin committed Jan 17, 2022
1 parent 33d98e2 commit 94d4662
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/material/select/select.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3175,6 +3175,16 @@ describe('MatSelect', () => {

expect(trigger.textContent).not.toContain('Pizza');
}));

it('should sync up the form control value with the component value', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectOnPushPreselected);
fixture.detectChanges();
flush();

expect(fixture.componentInstance.control.value).toBe('pizza-1');
expect(fixture.componentInstance.select.value).toBe('pizza-1');
}));

});

describe('with custom trigger', () => {
Expand Down Expand Up @@ -5426,6 +5436,7 @@ class BasicSelectOnPush {
`,
})
class BasicSelectOnPushPreselected {
@ViewChild(MatSelect) select: MatSelect;
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
Expand Down
6 changes: 5 additions & 1 deletion src/material/select/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,11 @@ export abstract class _MatSelectBase<C>
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value);
if (this.ngControl) {
this._value = this.ngControl.value;
}

this._setSelectionByValue(this._value);
this.stateChanges.next();
});
}
Expand Down

0 comments on commit 94d4662

Please sign in to comment.