Angular Material-下拉订单项按字母顺序 [英] Angular Material - dropdown order items alphabetically

查看:60
本文介绍了Angular Material-下拉订单项按字母顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有用户名的下拉列表.我想按字母顺序排序.我怎样才能做到这一点?

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>

推荐答案

,您可以为此构建自定义的OrderBy管道.

you can build a custom OrderBy Pipe for this.

例如,下面的OrderBy管道将根据您传递给对象数组key用字母或基于值(顺序: asc )进行排序:

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">`

不要忘记将OrderByPipe添加到NgModuledeclarations中.

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

UPD:

由@DeborahK和有角附录附录 无FilterPipe或OrderByPipe (最后一部分),OrderBy带有不正确的Pipe可能会导致性能问题,因此在这里,我提供了一个纯Pipe,这意味着您可以确定何时触发OrderBy Pipe,并提供输入数组一个新实例或更改转换为Pipe的参数.

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.

这篇关于Angular Material-下拉订单项按字母顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆