fix(autocomplete): handle attaching autocomplete to a number input (#9672)

Fixes the value being typed inside an `input[type="number"]` getting assigned to the model as a string. Normally this is handled by the `NumberValueAccessor` from the forms module, however the autocomplete is its own value accessor and as such has to handle it on its own.

Fixes #9628.
This commit is contained in:
Kristiyan Kostadinov
2018-02-01 20:26:56 +01:00
committed by tinayuangao
parent 26b0635d1f
commit f75fa15fc1
2 changed files with 37 additions and 1 deletions
+9 -1
View File
@@ -305,7 +305,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
// event on focus/blur/load if the input has a placeholder. See:
// https://connect.microsoft.com/IE/feedback/details/885747/
if (this._canOpen() && document.activeElement === event.target) {
this._onChange((event.target as HTMLInputElement).value);
let target = event.target as HTMLInputElement;
let value: number | string | null = target.value;
// Based on `NumberValueAccessor` from forms.
if (target.type === 'number') {
value = value == '' ? null : parseFloat(value);
}
this._onChange(value);
this.openPanel();
}
}
+28
View File
@@ -1639,6 +1639,17 @@ describe('MatAutocomplete', () => {
expect(trigger.panelOpen).toBe(false, 'Expected panel to be closed.');
}));
it('should handle autocomplete being attached to number inputs', fakeAsync(() => {
const fixture = createComponent(AutocompleteWithNumberInputAndNgModel);
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input')).nativeElement;
typeInElement('1337', input);
fixture.detectChanges();
expect(fixture.componentInstance.selectedValue).toBe(1337);
}));
});
it('should have correct width when opened', () => {
@@ -2072,3 +2083,20 @@ class AutocompleteWithSelectEvent {
class PlainAutocompleteInputWithFormControl {
formControl = new FormControl();
}
@Component({
template: `
<mat-form-field>
<input type="number" matInput [matAutocomplete]="auto" [(ngModel)]="selectedValue">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let value of values" [value]="value">{{value}}</mat-option>
</mat-autocomplete>
`
})
class AutocompleteWithNumberInputAndNgModel {
selectedValue: number;
values = [1, 2, 3];
}