Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows:

   console.log(this.paymentTypeData);
Array(5)
0: {value: "DAILY", code: "D", label: "Daily"}
1: {value: "SINGLE_TIER", code: "ST", label: "Single Tier"}
2: {value: "MULTI_TIER", code: "MT", label: "Multi Tier"}
3: {value: "NO_DISCOUNT", code: "ND", label: "No Discount"}
4: {value: "EOM", code: "EOM", label: "End of Month"}
length: 5
__proto__: Array(0)

The Current Order is:

  • Daily
  • Single Tier
  • Multi Tier
  • No Discount
  • End of Month

However, I would like to display them in the following order:

  • No Discount
  • Single Tier
  • Daily
  • Multi Tier
  • End of Month

HTML:

  <select
   class="form-control">
  <option *ngFor="let list of paymentTypeData" [ngValue]="list.code">
   {{list.label}}
   </option>
   </select>

Typescript:

public paymentTypeData: any;
     
     this.supplier.getPayTermTypes().subscribe(paymentTypes => {
     this.paymentTypeData = paymentTypes;
});

Answer №1

To improve the organization of your paymentTypes data, consider incorporating a sortOrder attribute. This way, when retrieving the paymentTypes, you can easily arrange them based on this specified order.

Ensure to sort the paymentTypeData using the following logic:
this.paymentTypeData.sort((a,b) => a.sortOrder > b.sortOder ? -1 : 1;

Answer №2

It is suggested that implementing Lotte Lemmens' solution of incorporating a sortOrder on the back-end would be more effective than adding it on the front-end.

If altering the back-end is not possible, an alternative approach is to create a lookup table within the front-end to determine the sorting order.

Assign each key in the table with the corresponding value of the property being sorted, such as "value":

const sortOrderTable = {
  "DAILY": 0,
  "SINGLE_TIER": 0,
  "MULTI_TIER": 0,
  "NO_DISCOUNT": 0,
  "EOM": 0
}

Adjust the values in the table to match your desired sorting sequence.

Lastly, modify your request in your .ts file to execute the sorting using a pipe:

this.supplier.getPayTermTypes()
  .pipe(
    map(apiResponse => apiResponse.sort((a,b) => sortOrderTable[a.value] > sortOrderTable[b.value] ? -1 : 1)))
  .subscribe(paymentTypes => {this.paymentTypeData=paymentTypes;});

Note: This method may be fragile as it depends on the response object's property name from the server remaining unchanged to align with the sort order table.

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

Step-by-step guide on importing Nano (CouchDB) using Typescript

I am facing difficulty in importing and using nano in my node application. According to the documentation, the JavaScript way is: var nano = require('nano')('http://localhost:5984'); How can I achieve this with TypeScript? I attempt ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

Why should TypeScript interfaces be utilized in Angular services for defining type information?

What are the benefits of creating an interface for an Angular service as opposed to simply exporting the service class and using that for type information? For example: class Dashboard { constructor(ui: IUiService){} } vs class Dashboard { cons ...

Is it possible to utilize [(ngModel)] in all components when including FormsModule in the app.module.ts file?

Is it possible to utilize [(ngModel)] in every component after importing FormsModule in app.module.ts? In app.module.ts import { FormsModule } from '@angular/forms'; Implementing in another component In view.component.html input type="text" ...

Creating React components dynamically using the number of objects passed as props

When attempting to create components based on the number specified in an object's files property, I keep encountering an error indicating that the parent component has too many children. If the files property is set to 5, does anyone have a solution ...

Align the headers of columns to the right in the AgGrid widget

Is there a way to align the column headers to the right in AgGrid without having to implement a custom header component? It seems like a lot of work for something that should be simple. You can see an example here: https://stackblitz.com/edit/angular-ag-g ...

What is the best way to navigate through this array within my nextjs/typescript/fetch application?

Having trouble finding a way to efficiently search through the CustomersList array. Any help would be greatly appreciated. Here's what happens after fetching the data: const data = await res.json(); return { props: { CustomersList: data, ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

Error with Array type encountered in Typescript's find method

I am encountering an issue with code that looks like this: type X = { test: number; x: number; }[]; type Y = { test: number; y: number; }[]; type Z = { test: number; z: number; }[]; export const testFunc = (arg: X | Y | Z) => { return a ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

The ASP.NET Core Web API successfully sends back a response, but unfortunately, the frontend is only seeing an empty value along with a status code of 200 (OK)

Currently, I am delving into the world of web APIs and have stumbled upon a perplexing issue that requires assistance. I have an active ASP.NET Core Web API at the backend, while at the frontend, an Angular application (running on version 15.1.5) is in pl ...

What is the best way to set a boolean value for a checkbox in a React project with Typescript?

Currently, I am working on a project involving a to-do list and I am facing an issue with assigning a boolean value to my checkbox. After array mapping my to-dos, the checkbox object displays 'on' when it is unchecked and a 'Synthetic Base E ...

Angular: StaticInjectorError(ExplorationEditorPageModule)[Number]

Currently in the process of transitioning oppia's codebase from AngularJS(1.x) to Angular(2+). I recently migrated a service called UtilsService.ts to the following code snippet: import { Injectable } from '@angular/core'; import { downgrad ...

Property 'text' is not found on type '{} | Response' in Angular/Node

After making changes to my angular project's package.json by downgrading from version 4.2.4 to 4.1.3 and then upgrading back to 4.2.4, I encountered an error while building the project: $ ng build Your global Angular CLI version (1.5.0) is greater ...

When utilizing useRef and useCallback in React, the output is visible in the console log but does not appear on the page

When working with API data, it's important to remember that the extraction process is asynchronous and the state may not be available at certain times. To handle this situation, we can utilize useCallback. However, even after successfully logging the ...

Setting an expiry date for Firestore documents

Is it feasible to set a future date and time in a firestore document and trigger a function when that deadline is reached? Let's say, today I create a document and specify a date for the published field to be set to false fifteen days later. Can this ...

What is the significance of `/// <reference types="react-scripts" />` in programming? Are there any other XML-like syntaxes that are commonly used in *.d.ts

When working with normal *.d.ts files (which are definition files for TypeScript), we typically use declare *** export interface *** However, there is also this syntax: /// <reference types="react-scripts" /> This syntax is generated by create- ...

Potential breakpoint (Breakpoint established but not yet linked)

My experience with debugging my Angular app in Chrome was going smoothly through the Chrome Debugger extension with automatic settings. However, something changed after a Windows 7 reboot and all my breakpoints became inactive. I suspect this was due to a ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

Clicking on a component in Nuxt will trigger it to open

Is there a way to trigger a modal window to open when a button is clicked without storing the modal window in the header? file header: <template> <section class="header"> <div class="header-container"> ...