Skip to content

Commit a64a1c2

Browse files
committed
fix(autocomplete): allow number zero as value
* Currently the autocomplete does not properly display the selected options with the number zero as value. Fixes #5363.
1 parent 38b365c commit a64a1c2

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/lib/autocomplete/autocomplete-trigger.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,9 @@ export class MdAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
358358

359359
private _setTriggerValue(value: any): void {
360360
const toDisplay = this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value;
361-
this._element.nativeElement.value = toDisplay || '';
361+
// Simply falling back to an empty string if the display value is falsy does not work properly.
362+
// The display value can also be the number zero and shouldn't fallback to an empty string.
363+
this._element.nativeElement.value = toDisplay != null ? toDisplay : '';
362364
}
363365

364366
/**

src/lib/autocomplete/autocomplete.spec.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ describe('MdAutocomplete', () => {
5353
AutocompleteWithoutForms,
5454
NgIfAutocomplete,
5555
AutocompleteWithNgModel,
56+
AutocompleteWithNumbers,
5657
AutocompleteWithOnPushDelay,
5758
AutocompleteWithNativeInput,
5859
AutocompleteWithoutPanel
@@ -1136,6 +1137,19 @@ describe('MdAutocomplete', () => {
11361137
});
11371138
}));
11381139

1140+
it('should display the number when the selected option is the number zero', async(() => {
1141+
const fixture = TestBed.createComponent(AutocompleteWithNumbers);
1142+
1143+
fixture.componentInstance.selectedNumber = 0;
1144+
fixture.detectChanges();
1145+
1146+
fixture.whenStable().then(() => {
1147+
const input = fixture.debugElement.query(By.css('input')).nativeElement;
1148+
1149+
expect(input.value).toBe('0');
1150+
});
1151+
}));
1152+
11391153
it('should work when input is wrapped in ngIf', async(() => {
11401154
const fixture = TestBed.createComponent(NgIfAutocomplete);
11411155
fixture.detectChanges();
@@ -1404,6 +1418,23 @@ class AutocompleteWithNgModel {
14041418

14051419
}
14061420

1421+
@Component({
1422+
template: `
1423+
<md-input-container>
1424+
<input mdInput placeholder="Number" [mdAutocomplete]="auto" [(ngModel)]="selectedNumber">
1425+
</md-input-container>
1426+
1427+
<md-autocomplete #auto="mdAutocomplete">
1428+
<md-option *ngFor="let number of numbers" [value]="number">
1429+
<span>{{ number }}</span>
1430+
</md-option>
1431+
</md-autocomplete>
1432+
`
1433+
})
1434+
class AutocompleteWithNumbers {
1435+
selectedNumber: number;
1436+
numbers = [0, 1, 2];
1437+
}
14071438

14081439
@Component({
14091440
changeDetection: ChangeDetectionStrategy.OnPush,

0 commit comments

Comments
 (0)