Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project.

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

In this case, the displayed option name is determined by whether each item has a name or identity. If there is a name, it will be shown, otherwise the identity will be used.

I came across a Stack Overflow post recommending a custom orderBy pipe for sorting options alphabetically Angular Material - dropdown order items alphabetically

However, this method sorts based on a single key. I lack experience in creating custom pipes. How can I adapt this approach to meet my specific requirements?

Answer №1

A more efficient approach would be to develop a reusable pipe that can be utilized across the entire project. Here's an example:

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

You can then use it like this:

<mat-option *ngFor="let item of items | 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

Click here for additional details.

Answer №2

It is recommended that the data be sorted alphabetically from the backend source.

There is no 'orderBy' pipe available because the Angular team expects the data to already be sorted, as indicated in the documentation at https://angular.io/guide/pipes

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Import JSON data into Angular 2 Component

After much effort, I have finally figured out how to load JSON data into an Angular 2 Component. datoer.service.ts: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from ...

.bail() function does not function properly when used in conjunction with express-validator

While registering a new user, I require their name, email, and password. If no name is provided, there is no need for the backend to validate the email. I believe that the use of .bail() in express-validator should handle this situation, but unfortunately ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

Set the variable value by clicking on another component within *ngFor in Angular 2

I am attempting to use *ngFor to pass an object to another component, but only the last object in the table is being passed. The object that was clicked should be displayed instead. How can I solve this issue? <tr data-toggle="control-sidebar" *ngFor=" ...

Implementing a SetTimeout Function in HTML

Is there a way to delay calling the mouseHoverTableRow() function until after hovering on tr for 3 seconds? I only want to call this function if the hover duration is at least 3 seconds, as it triggers an API request. How can I achieve this? <tr *ngF ...

Unraveling the complexities of Typescript's Advanced Type NonFunctionPropertyNames

Delving deeper into the realm of advanced types in Typescript, I came across an intriguing type called NonFunctionPropertyNames. This type is designed to extract only the properties of a given object that are not functions. type NonFunctionPropertyNames&l ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Having trouble with updating operations in MEAN stack CRUD functionalities

While implementing CRUD operations, I encountered an issue with the update function. Even though I followed a tutorial (https://www.youtube.com/watch?v=fhRdqbEXp9Y) and customized the code to suit my application, the update operation is not working as expe ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

Changing the second instance of a specific text in Angular

str = "oreo has oreo"; switch the 2nd instance of oreo with chocolate result = "oreo has choklate"; how to change specific occurrence of a string in Angular 8. ...

What steps can be taken to ensure the visibility and accessibility of two vertically stacked/overlapped Html input elements in HTML?

I have encountered a challenge with my HTML input elements. There are two input elements that overlap each other, and I would like to make both inputs visible while only allowing the top input to be editable. I have tried several approaches involving z-ind ...

Resolve routing problems with lazy loading in Angular7

I have been working on implementing lazy loading in my Angular project. However, I am encountering the same error even after following the suggested solution. Lazy loading error on StackOverflow I have exported the components from the project module and im ...

After being awaited recursively, the resolved promise does not perform any actions

When working with the Twitter API, I need to make recursive method calls to retrieve tweets since each request only returns a maximum of 100 tweets. The process is straightforward: Call the function and await it Make an HTTP request and await that If the ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

Having trouble reloading a seekbar (input range) in Angular 7 with a function?

I am currently in the process of developing a music player using Angular 7, and below is the HTML code for my component: <div class="track-controller"> <small>{{musicPlayerService.getCurrentTime()}}</small> <div class="progress- ...

Tips for utilizing Optical Character Recognition in Node.js with a buffer image:

Are you facing difficulties in creating an API that extracts data from an image without saving it on the server? Look no further, as I have a solution for you. When testing with the URL '', everything works perfectly. However, using a buffer or l ...