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

Retrieving the component's values when utilizing the `<ng-content>` directive

Seeking a technique for accessing the values of a component when utilizing <ng-content>: import {Component} from '@angular/core'; @Component({ selector: 'home-page', template: `<person-box>{{name}}</person-box> & ...

Deleting ion-radio from ion-select component in Ionic v4

Is there a way to remove ion-radio elements generated when calling ion-select with a popover interface? <ion-item> <ion-label>Popover</ion-label> <ion-select interface="popover" placeholder="Select One"> <ion-selec ...

Encountering an error while utilizing ngForm in an HTML form

I have developed a custom component called "login", where I created an HTML form named "login.component.html". To convert this form into an Angular form, I added the code "" in login.component.html and imported import {NgForm} from '@angular/forms&apo ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

How can I implement a button in Angular Ag Grid to delete a row in a cell render

I have included a button within a cell that I want to function as a row deleter. Upon clicking, it should remove the respective row of data and update the grid accordingly. Check out the recreation here:https://stackblitz.com/edit/row-delete-angular-btn-c ...

Restful: Numerous scenarios for a single resource (is it the same API endpoint?)

In this scenario, there are two different approaches to creating a user: If the user is created by an administrator, no password is provided initially. The user must choose a password on the activation page. If the user creates their own account, a passw ...

Guide on initiating document-wide events using Jasmine tests in Angular 2/4

As stated in the Angular Testing guidelines, triggering events from tests requires using the triggerEventHandler() method on the debug element. This method accepts the event name and the object. It is effective when adding events with HostListener, such as ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Steps to access a Request object within a Controller

I am currently working with Express and Typescript, utilizing Controllers for managing requests. In an attempt to create a BaseController that includes the Request and Response objects for each request, I wrote the following code snippet. However, it see ...

Angular powered bootstrap modal with a clean and sleek design featuring a transparent header and background

Currently, I am utilizing an Angular-powered Bootstrap modal for a project. The modal content consists of an iframe that functions as a YouTube video player. My objective is to have the background colors of both the modal body and header be transparent, so ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

Angular - failure to detect function execution by spy

I've been trying to test a feature module, but I'm facing some difficulties. The last test is failing because the spy isn't detecting that the method is being called, even when I move the this.translate.use(this.currentLanguage.i18n) call ou ...

Troubleshooting problems with routing for an Angular 5 single page application when serving it from a Lumen 5.2 controller

I am facing an issue with serving an Angular SPA from a single routed Lumen endpoint. While the initial boot of the Angular application works fine when navigating directly to the endpoint, loading any child route of the Angular SPA does not work properly. ...

Using React and Typescript: Populating an array within a For Loop using setTimeout is not happening sequentially or at all

I'm currently working on a function that animates images of random cars moving across the screen. My goal is to stagger the population of the "carsLeft" array using setTimeout, where I will eventually randomize the delay time for each car. Everything ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Error: Could not inject CookieService - No provider found for CookieService

I am currently working on an ASP.NET Core 2.0 project that incorporates an Angular 5.1.0 ClientApp in Visual Studio 2017 v15.4.5. My goal is to utilize the ngx-cookie-service within this setup. After closely following the provided instructions for importi ...

Creating a message factory in Typescript using generics

One scenario in my application requires me to define message structures using a simple TypeScript generic along with a basic message factory. Here is the solution I devised: export type Message< T extends string, P extends Record<string, any> ...