Skip to content

Commit f75fa15

Browse files
crisbetotinayuangao
authored andcommitted
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.
1 parent 26b0635 commit f75fa15

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/lib/autocomplete/autocomplete-trigger.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
305305
// event on focus/blur/load if the input has a placeholder. See:
306306
// https://connect.microsoft.com/IE/feedback/details/885747/
307307
if (this._canOpen() && document.activeElement === event.target) {
308-
this._onChange((event.target as HTMLInputElement).value);
308+
let target = event.target as HTMLInputElement;
309+
let value: number | string | null = target.value;
310+
311+
// Based on `NumberValueAccessor` from forms.
312+
if (target.type === 'number') {
313+
value = value == '' ? null : parseFloat(value);
314+
}
315+
316+
this._onChange(value);
309317
this.openPanel();
310318
}
311319
}

src/lib/autocomplete/autocomplete.spec.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,6 +1639,17 @@ describe('MatAutocomplete', () => {
16391639
expect(trigger.panelOpen).toBe(false, 'Expected panel to be closed.');
16401640
}));
16411641

1642+
it('should handle autocomplete being attached to number inputs', fakeAsync(() => {
1643+
const fixture = createComponent(AutocompleteWithNumberInputAndNgModel);
1644+
fixture.detectChanges();
1645+
const input = fixture.debugElement.query(By.css('input')).nativeElement;
1646+
1647+
typeInElement('1337', input);
1648+
fixture.detectChanges();
1649+
1650+
expect(fixture.componentInstance.selectedValue).toBe(1337);
1651+
}));
1652+
16421653
});
16431654

16441655
it('should have correct width when opened', () => {
@@ -2072,3 +2083,20 @@ class AutocompleteWithSelectEvent {
20722083
class PlainAutocompleteInputWithFormControl {
20732084
formControl = new FormControl();
20742085
}
2086+
2087+
2088+
@Component({
2089+
template: `
2090+
<mat-form-field>
2091+
<input type="number" matInput [matAutocomplete]="auto" [(ngModel)]="selectedValue">
2092+
</mat-form-field>
2093+
2094+
<mat-autocomplete #auto="matAutocomplete">
2095+
<mat-option *ngFor="let value of values" [value]="value">{{value}}</mat-option>
2096+
</mat-autocomplete>
2097+
`
2098+
})
2099+
class AutocompleteWithNumberInputAndNgModel {
2100+
selectedValue: number;
2101+
values = [1, 2, 3];
2102+
}

0 commit comments

Comments
 (0)