Search code examples
angulartypescriptangular-pipe

How to order mat-select alphabetically when options have conditional names


I have this mat-select that I want to order alphabetically.

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

The name of the option displayed is conditional. Each item will have an optional name. If it does have a name then it will be used, otherwise the identity name will be used.

I've seen on SO that it is suggested to make a custom orderBy pipe something like this answer Angular Material - dropdown order items alphabetically

But that sorts using a single key. I'm not very experienced in making custom pipes. How would this work for my case?


Solution

  • Better to create a pipe which can be used for entire project, like this:

    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;
                }
            });
        };
    }
    

    And then you can use it like:

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

    Note: column=> any property, direction(1 or -1) => for ascending/descending

    For more detail see this