【问题标题】:Angular Material - dropdown order items alphabeticallyAngular Material - 按字母顺序排列的下拉顺序项目
【发布时间】:2017-05-11 16:44:56
【问题描述】:

我有一个包含用户名的下拉菜单。我想按字母顺序排列。我怎样才能做到这一点?

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

【问题讨论】:

    标签: angularjs angular-material angular-material2


    【解决方案1】:

    您可以为此构建自定义OrderBy 管道。

    例如,下面的 OrderBy Pipe 将按您传递给它的key对象数组 进行排序,并按字母顺序或基于值(顺序: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;
          }
        });
      }
    

    }

    在您的模板中如下:

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

    不要忘记将OrderByPipe 添加到您的declarationsNgModule

    UPD:

    正如@DeborahK 和角度附录No FilterPipe or OrderByPipe(最后一部分)回答的那样,OrderBy 使用不纯 Pipe 可能会导致性能问题,所以在这里我提供一个纯 Pipe 这意味着您可以确定何时触发 OrderBy Pipe,即为输入 Array 提供一个新实例或更改转换为 Pipe 的参数。

    Plunker Demo.

    【讨论】:

    • 构建 OrderBy 管道存在潜在的性能问题。来自文档:The Angular team and many experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself...If these performance and minification considerations don't apply to you, you can always create your own such pipes (similar to the FlyingHeroesPipe) or find them in the community. 请参阅此处的附录:angular.io/docs/ts/latest/guide/pipes.html
    • @DeborahK 我知道性能问题。 thah 为什么在这里我提供纯管道,并且 OP 可以确定何时触发管道。如果还有任何问题,请告诉我,很高兴学习。
    【解决方案2】:

    考虑对组件类中的用户集进行排序。然后在 ngFor 中使用就可以了。

    如果您可以提供用于构建/检索用户数组的组件类代码,我们可以提供更具体的排序建议。

    您可以在此处找到排序方法的文档: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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多