Components: Select default values not working for objects

Created on 17 Apr 2018  路  4Comments  路  Source: angular/components

Bug, feature request, or proposal:

Proposal, (maybe) Bug

What is the expected behavior?

Select should allow for default selected values that are not strings.

What is the current behavior?

MatSelect does not allow for default selected values if the values being used are any datatype other than strings.

For example, I frequently use *ngFor to create an option list, and then use an object as the value of a MatOption to be able to store/use more than just a string when a user selects a value.

What are the steps to reproduce?

https://stackblitz.com/edit/angular-material2-issue-default-select

What is the use-case or motivation for changing an existing behavior?

I always use objects as values for MatOption inside MatSelect because an object is much more useful than a string value when a user selects an option.

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular 5.2.x
Angular Material 5.2.x

Is there anything else we should know?

I have a feeling there is a better (more correct) way to be able to link an object to a MatSelect option, but passing it in as a value seems most intuitive to me.

Most helpful comment

The following is from material.angular.io/components/select/api

@Input()
compareWith: (o1: any, o2: any) => boolean

A function to compare the option values with the selected values. The first argument is a value from an option. The second is a value from the selection. A boolean should be returned.

Using that it should be possible to solve the problem.

All 4 comments

To make the last select show the default value change the code to this:

optionsObjects = [
  {value: 1, display: 'Option 1'},
  {value: 2, display: 'Option 2'},
  {value: 3, display: 'Option 3'},
];
selectedObject = this.optionsObjects[0];

The third box has the same problem, the object reference is not the same.

The following is from material.angular.io/components/select/api

@Input()
compareWith: (o1: any, o2: any) => boolean

A function to compare the option values with the selected values. The first argument is a value from an option. The second is a value from the selection. A boolean should be returned.

Using that it should be possible to solve the problem.

@mucbits is correct, mat-select compares the objects by reference by default. You can use compareWith to have some custom comparison logic.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings