Angular Material - dropdown order items alphabetically

耗尽温柔 提交于 2020-05-31 06:36:09

问题


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>

回答1:


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.




回答2:


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']


来源:https://stackoverflow.com/questions/43921319/angular-material-dropdown-order-items-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!