Skip to content

Commit 94d4662

Browse files
crisbetoandrewseguin
authored andcommitted
fix(select): component value not in sync with control value on init (#18443)
Fixes the `MatSelect.value` property not being in sync with the `ControlValueAccessor` initial value on init. Fixes #18423. (cherry picked from commit 99c6112)
1 parent 33d98e2 commit 94d4662

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/material/select/select.spec.ts

+11
Original file line numberDiff line numberDiff line change
@@ -3175,6 +3175,16 @@ describe('MatSelect', () => {
31753175

31763176
expect(trigger.textContent).not.toContain('Pizza');
31773177
}));
3178+
3179+
it('should sync up the form control value with the component value', fakeAsync(() => {
3180+
const fixture = TestBed.createComponent(BasicSelectOnPushPreselected);
3181+
fixture.detectChanges();
3182+
flush();
3183+
3184+
expect(fixture.componentInstance.control.value).toBe('pizza-1');
3185+
expect(fixture.componentInstance.select.value).toBe('pizza-1');
3186+
}));
3187+
31783188
});
31793189

31803190
describe('with custom trigger', () => {
@@ -5426,6 +5436,7 @@ class BasicSelectOnPush {
54265436
`,
54275437
})
54285438
class BasicSelectOnPushPreselected {
5439+
@ViewChild(MatSelect) select: MatSelect;
54295440
foods: any[] = [
54305441
{value: 'steak-0', viewValue: 'Steak'},
54315442
{value: 'pizza-1', viewValue: 'Pizza'},

src/material/select/select.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,11 @@ export abstract class _MatSelectBase<C>
831831
// Defer setting the value in order to avoid the "Expression
832832
// has changed after it was checked" errors from Angular.
833833
Promise.resolve().then(() => {
834-
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value);
834+
if (this.ngControl) {
835+
this._value = this.ngControl.value;
836+
}
837+
838+
this._setSelectionByValue(this._value);
835839
this.stateChanges.next();
836840
});
837841
}

0 commit comments

Comments
 (0)