Navigation Menu

Skip to content

Commit

Permalink
fix(datepicker): not respecting form control updateOn: blur fo… (#18063)
Browse files Browse the repository at this point in the history
Fixes the datepicker input not respecting when a `FormControl` is set to `updateOn: 'blur'` when changing between invalid values. The input was emitting for each change like the default.

Fixes #16461.
  • Loading branch information
crisbeto authored and mmalerba committed Dec 29, 2019
1 parent a30094b commit 61029c8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/material/datepicker/datepicker-input.ts
Expand Up @@ -320,6 +320,7 @@ export class MatDatepickerInput<D> implements ControlValueAccessor, OnDestroy, V
}

_onInput(value: string) {
const lastValueWasValid = this._lastValueValid;
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
this._lastValueValid = !date || this._dateAdapter.isValid(date);
date = this._getValidDateOrNull(date);
Expand All @@ -329,7 +330,7 @@ export class MatDatepickerInput<D> implements ControlValueAccessor, OnDestroy, V
this._cvaOnChange(date);
this._valueChange.emit(date);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
} else {
} else if (lastValueWasValid !== this._lastValueValid) {
this._validatorOnChange();
}
}
Expand Down
38 changes: 38 additions & 0 deletions src/material/datepicker/datepicker.spec.ts
Expand Up @@ -876,6 +876,44 @@ describe('MatDatepicker', () => {

expect(testComponent.datepickerToggle.disabled).toBe(true);
});

it('should not dispatch FormControl change event for invalid values on input when set ' +
'to update on blur', fakeAsync(() => {
const formControl = new FormControl({value: null}, {updateOn: 'blur'});
const spy = jasmine.createSpy('change spy');
const subscription = formControl.valueChanges.subscribe(spy);
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
const setValue = (value: string) => {
inputEl.value = value;
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
flush();
fixture.detectChanges();
};

fixture.componentInstance.formControl = formControl;
fixture.detectChanges();

expect(spy).not.toHaveBeenCalled();

setValue('10/10/2010');
expect(spy).not.toHaveBeenCalled();

setValue('10/10/');
expect(spy).not.toHaveBeenCalled();

setValue('10/10');
expect(spy).not.toHaveBeenCalled();

dispatchFakeEvent(inputEl, 'blur');
fixture.detectChanges();
flush();
fixture.detectChanges();

expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
}));

});

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

0 comments on commit 61029c8

Please sign in to comment.