Skip to content

Commit

Permalink
fix(autocomplete): handle attaching autocomplete to a number input (#…
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
crisbeto authored and tinayuangao committed Feb 1, 2018
1 parent 26b0635 commit f75fa15
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/lib/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
Expand Down
28 changes: 28 additions & 0 deletions src/lib/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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];
}

0 comments on commit f75fa15

Please sign in to comment.