Skip to content

Commit

Permalink
fix(select): unable to programmatically select falsy values
Browse files Browse the repository at this point in the history
Fixes not being able to set falsy values progammatically in `md-select`.

Fixes angular#4854.
  • Loading branch information
crisbeto committed May 29, 2017
1 parent 12d6e96 commit 99ecc03
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
36 changes: 35 additions & 1 deletion src/lib/select/select.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ describe('MdSelect', () => {
BasicSelectInitiallyHidden,
BasicSelectNoPlaceholder,
BasicSelectWithTheming,
ResetValuesSelect
ResetValuesSelect,
FalsyValueSelect
],
providers: [
{provide: OverlayContainer, useFactory: () => {
Expand Down Expand Up @@ -449,6 +450,22 @@ describe('MdSelect', () => {
expect(fixture.componentInstance.select.selected).not.toBeDefined();
});

it('should be able to programmatically select a falsy option', () => {
fixture.destroy();

let falsyFixture = TestBed.createComponent(FalsyValueSelect);

falsyFixture.detectChanges();
falsyFixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement.click();
falsyFixture.componentInstance.control.setValue(0);
falsyFixture.detectChanges();

expect(falsyFixture.componentInstance.options.first.selected)
.toBe(true, 'Expected first option to be selected');
expect(overlayContainerElement.querySelectorAll('md-option')[0].classList)
.toContain('mat-selected', 'Expected first option to be selected');
});

});

describe('forms integration', () => {
Expand Down Expand Up @@ -2504,3 +2521,20 @@ class ResetValuesSelect {

@ViewChild(MdSelect) select: MdSelect;
}


@Component({
template: `
<md-select [formControl]="control">
<md-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }}</md-option>
</md-select>
`
})
class FalsyValueSelect {
foods: any[] = [
{ value: 0, viewValue: 'Steak' },
{ value: 1, viewValue: 'Pizza' },
];
control = new FormControl();
@ViewChildren(MdOption) options: QueryList<MdOption>;
}
4 changes: 3 additions & 1 deletion src/lib/select/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,9 @@ export class MdSelect implements AfterContentInit, OnDestroy, OnInit, ControlVal
*/
private _selectValue(value: any): MdOption {
let optionsArray = this.options.toArray();
let correspondingOption = optionsArray.find(option => option.value && option.value === value);
let correspondingOption = optionsArray.find(option => {
return option.value != null && option.value === value;
});

if (correspondingOption) {
correspondingOption.select();
Expand Down

0 comments on commit 99ecc03

Please sign in to comment.