【问题标题】:How to order mat-select alphabetically when options have conditional namesHow to order mat-select alphabetically when options have conditional names
【发布时间】:2020-01-28 22:11:58
【问题描述】:

我有这个垫子选择,我想按字母顺序排列。

 <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)">
    <mat-option *ngFor="let item of itemss" [value]="item">
              {{ item.name ? item.name: item.identity}}
    </mat-option>
</mat-select>

显示的选项名称是有条件的。每个项目都有一个可选的名称。如果确实有名称,则将使用它,否则将使用身份名称。

我在 SO 上看到建议进行自定义 orderBy 管道类似于此答案Angular Material - dropdown order items alphabetically

但是使用单个键进行排序。我在制作定制管道方面不是很有经验。这对我的情况如何?

【问题讨论】:

    标签: angular typescript angular-pipe


    【解决方案1】:

    最好创建一个可用于整个项目的管道,如下所示:

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({  name: 'orderBy' })
    export class OrderrByPipe implements PipeTransform {
    
        transform(records: Array<any>, args?: any): any {
            return records.sort(function(a, b){
                if(a[args.property] < b[args.property]){
                    return -1 * args.direction;
                }
                else if( a[args.property] > b[args.property]){
                    return 1 * args.direction;
                }
                else{
                    return 0;
                }
            });
        };
    }
    

    然后你可以像这样使用它:

    <mat-option *ngFor="let item of itemss | orderBy: {property: column, direction: direction}"" [value]="item">
       {{ item.name ? item.name: item.identity}}
    </mat-option>
    

    注意:column=> 任何属性,方向(1 或 -1)=> 用于升序/降序

    For more detail see this

    【讨论】:

      【解决方案2】:

      理想情况下,数据应从后端按字母顺序排列。

      它没有“orderBy”管道,因为 Angular 团队认为它应该已经排序,根据 https://angular.io/guide/pipes 的文档

      【讨论】:

      • 欢迎来到stackoverflow。请考虑在为答案提供的空间中包含您链接中的一些相关信息
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 2022-12-27
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多