当选项具有条件名称时如何按字母顺序排序垫选择

Dea*_*dom 2 typescript angular-pipe angular

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

 <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>
Run Code Online (Sandbox Code Playgroud)

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

我在 SO 上看到建议制作一个自定义 orderBy 管道,类似于这个答案Angular Material - dropdown order items 按字母顺序排列

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

Ali*_*avi 5

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

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;
            }
        });
    };
}
Run Code Online (Sandbox Code Playgroud)

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

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

注意:column=> 任意属性,direction(1 或 -1) => 升序/降序

有关更多详细信息,请参阅此