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

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Deployment failure of AWS CDK caused by Error: Lambda Function Invalid

I'm in the process of integrating a Lambda authorizer into my REST API using AWS CDK. const api = new apigw.RestApi(this, 'apiname', { defaultCorsPreflightOptions: { allowOrigins: apigw.Cors.ALL_ORIGINS } }); const authorizerFuncti ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Developers can learn how to use Angular's built-in i18n feature to internationalize innerHtml

I am currently working on internationalizing a website using Angular's built-in i18n feature. However, it seems that there is an issue with the code as they are using innerHtml to display a warning message, and I am unable to find a way to internatio ...

what kind of bespoke entity in TypeScript

Exploring typescript for the first time, I have constructed this object: const startingState = { name: { value: "", error: false }, quantity: { value: 0, error: false }, category: "Grocery& ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

Installation and execution of TypeScript jQuery / Bootstrap definition file on a local machine using npm typings: A step-by-step guide

Struggling to set up TypeScript jQuery and Bootstrap definition files in my new project using npm typings. Below are the steps I followed: 1- Open cmd, navigate to my project folder, and enter the following commands: npm install typings --global typings ...

Retrieve all the characteristics accessible of a particular course

I am facing a situation where I have the following class structure: class A { id: number propertyA: string constructor(id: number) { this.id = id } } let a = new A(3) console.log(SomeFunction(a)) // expected output = ['id', ' ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Is it possible to use the provide() method with a string in Angular 2 when writing

I am attempting to utilize a String as a token for providing instead of a class: app.RandomComponent = ng.core .Component({ selector: "randomComponent", template: "Component!", providers: [ ng.core.provide("Stuff", ...

Angular 2 Dropdown Multiselect Plugin - Fully Customize Width to 100%

Currently working on integrating the angular-2-dropdown-multiselect component: https://www.npmjs.com/package/angular-2-dropdown-multiselect The component functions correctly, but I am looking to adjust its width to fit the container... I believe simply ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Issue with Angular 2 Custom Pipe not Refreshing Unless Object is Saved

I recently created a custom Angular 2 pipe that formats a phone number from a 10-digit string to 'XXX-XXX-XXXX'. The pipe is functioning perfectly, but the issue arises when it fails to update in real-time during keypress; instead, it updates onl ...

Using the "Range" Input Type in Angular's Reactive Forms

I'm having difficulties with styling the background of my slider/range in reactive forms within Angular. The input value updates correctly, but the issue arises when I try to type in the input field - the range changes, but the color (green) remains s ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

Angular firebase Error: The parameter 'result' is missing a specified type and is implicitly assigned the 'any' type

I have encountered an issue with the code I am working on and both the result and error are throwing errors: ERROR in src/app/login/phone/phone.component.ts(48,75): error TS7006: Parameter 'result' implicitly has an 'any' type. s ...

Having difficulty retrieving an angular file from a location outside of the asset folder

I'm encountering issues with a small project that is meant to read a log and present it in table format. Here is the outline of the project structure: project structure Within the LOG directory, I should be able to access motore.log from my DataServi ...