Jay
Jay

Reputation: 339

Angular Material - dropdown order items alphabetically

I have a dropdown with user names. I would like to order it alphabetically. How can I achieve this?

<md-select formControlName="user" id="user" style="min-width: 200px;">
                <md-option *ngFor="let user of users" [value]="user.id">
                    {{user.displayName}}
                </md-option>
            </md-select>

Upvotes: 1

Views: 5374

Answers (2)

Pengyy
Pengyy

Reputation: 38191

you can build a custom OrderBy Pipe for this.

For example the below OrderBy Pipe will sort the object array by the key you passed to it with alphabetically or value based (order: asc):

@Pipe({name: 'OrderBy'})
export class OrderByPipe implements PipeTranform {
  transform(input: any, key: string) {
    if (!input) return [];

    return input.sort(function(itemA, itemB) {
      if (itemA[key] > itemB[key]) {
        return 1;
      } else (itemA[key] < itemB[key]) {
        return -1;
      } else {
        return 0;
      }
    });
  }

}

and in your template as below:

<md-option *ngFor="let user of users | OrderBy: 'id'" [value]="user.id">`

don't forget to add OrderByPipe to your declarations of NgModule.

UPD:

as answered by @DeborahK and angular appendix No FilterPipe or OrderByPipe(last part), OrderBy with a impure Pipe may cause performance problem, so here I'm providing an pure Pipe which means you can determine when to fire the OrderBy Pipe which is give the input Array a new instance or change the parameter transformed to the Pipe.

Plunker Demo.

Upvotes: 3

DeborahK
DeborahK

Reputation: 60528

Consider sorting the set of users in the component class. Then it will be in order when its used in the ngFor.

If you can provide the component class code you are using to build/retrieve the users array, we could provide more specific suggestions for sorting it.

You can find the doc for the sort method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=example

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']

Upvotes: 0

Related Questions