Skip to content

Commit 184f866

Browse files
committed
fix(material/datepicker): value reset when invalid value is entered using signal forms
Fixes that the datepicker input value was being reset when the user types in an invalid date while using signal forms. Fixes #32475.
1 parent 0f26a3c commit 184f866

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/material/datepicker/datepicker-input-base.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection
8484
protected _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
8585
_dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
8686
private _dateFormats = inject<MatDateFormats>(MAT_DATE_FORMATS, {optional: true})!;
87+
private _hasSetInitialCvaValue: boolean;
8788

8889
/** Whether the component has been initialized. */
8990
private _isInitialized: boolean;
@@ -293,8 +294,9 @@ export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection
293294
writeValue(value: D): void {
294295
// We produce a different date object on each keystroke which can cause signal forms'
295296
// interop logic to keep calling `writeValue` with the same value as the user is typing.
296-
// Skip such cases since they can prevent the user from typing (see #32442).
297-
if (!value || value !== this.value) {
297+
// Skip such cases since they can prevent the user from typing (see #32442 and #32475).
298+
if (!this._hasSetInitialCvaValue || value !== this.value) {
299+
this._hasSetInitialCvaValue = true;
298300
this._assignValueProgrammatically(value);
299301
}
300302
}

src/material/datepicker/datepicker.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1176,6 +1176,21 @@ describe('MatDatepicker', () => {
11761176

11771177
expect(input.value).toBe('foo');
11781178
});
1179+
1180+
it('should not re-format the input value if the forms module re-assigns null', () => {
1181+
const input = fixture.nativeElement.querySelector('input');
1182+
testComponent.formControl.setValue(null);
1183+
fixture.detectChanges();
1184+
expect(input.value).toBe('');
1185+
1186+
// Note: this isn't how users would behave, but it captures
1187+
// the sequence of events with signal forms.
1188+
input.value = 'foo';
1189+
testComponent.formControl.setValue(null);
1190+
fixture.detectChanges();
1191+
1192+
expect(input.value).toBe('foo');
1193+
});
11791194
});
11801195

11811196
describe('datepicker with mat-datepicker-toggle', () => {

0 commit comments

Comments
 (0)