Skip to content

Commit 2e3910c

Browse files
crisbetoandrewseguin
authored andcommitted
fix(select): unable to programmatically select falsy values (#4868)
Fixes not being able to set falsy values progammatically in `md-select`. Fixes #4854.
1 parent ce9d253 commit 2e3910c

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/lib/select/select.spec.ts

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ describe('MdSelect', () => {
5656
BasicSelectInitiallyHidden,
5757
BasicSelectNoPlaceholder,
5858
BasicSelectWithTheming,
59-
ResetValuesSelect
59+
ResetValuesSelect,
60+
FalsyValueSelect
6061
],
6162
providers: [
6263
{provide: OverlayContainer, useFactory: () => {
@@ -631,6 +632,22 @@ describe('MdSelect', () => {
631632
.toContain('*', `Expected placeholder to have an asterisk, as control was required.`);
632633
});
633634

635+
it('should be able to programmatically select a falsy option', () => {
636+
fixture.destroy();
637+
638+
const falsyFixture = TestBed.createComponent(FalsyValueSelect);
639+
640+
falsyFixture.detectChanges();
641+
falsyFixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
642+
falsyFixture.componentInstance.control.setValue(0);
643+
falsyFixture.detectChanges();
644+
645+
expect(falsyFixture.componentInstance.options.first.selected)
646+
.toBe(true, 'Expected first option to be selected');
647+
expect(overlayContainerElement.querySelectorAll('md-option')[0].classList)
648+
.toContain('mat-selected', 'Expected first option to be selected');
649+
});
650+
634651
});
635652

636653
describe('disabled behavior', () => {
@@ -2516,3 +2533,20 @@ class ResetValuesSelect {
25162533

25172534
@ViewChild(MdSelect) select: MdSelect;
25182535
}
2536+
2537+
2538+
@Component({
2539+
template: `
2540+
<md-select [formControl]="control">
2541+
<md-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }}</md-option>
2542+
</md-select>
2543+
`
2544+
})
2545+
class FalsyValueSelect {
2546+
foods: any[] = [
2547+
{ value: 0, viewValue: 'Steak' },
2548+
{ value: 1, viewValue: 'Pizza' },
2549+
];
2550+
control = new FormControl();
2551+
@ViewChildren(MdOption) options: QueryList<MdOption>;
2552+
}

src/lib/select/select.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,9 @@ export class MdSelect implements AfterContentInit, OnDestroy, OnInit, ControlVal
582582
*/
583583
private _selectValue(value: any): MdOption {
584584
let optionsArray = this.options.toArray();
585-
let correspondingOption = optionsArray.find(option => option.value && option.value === value);
585+
let correspondingOption = optionsArray.find(option => {
586+
return option.value != null && option.value === value;
587+
});
586588

587589
if (correspondingOption) {
588590
correspondingOption.select();

0 commit comments

Comments
 (0)