Prince
Prince

Reputation: 317

How to sort options in select dropdown in Angular?

I have been trying to sort the options in the select dropdown in Angular 9. I tried using orderBy and sort pipe but that didn't work out. I think it doesn't support this version of angular. Is there any other pipe for sorting or what another way I can achieve this?

Here is a demo code on StackBlitz: https://stackblitz.com/edit/angular-pmr4a6?file=app/select-reset-example.ts

Upvotes: 1

Views: 1306

Answers (1)

Pharcyde
Pharcyde

Reputation: 173

Angular 9 does not support the orderBy pipe anymore. Just add a .sort() to the array (will sort a string array alphabetically by default but you can provide a custom sort method):

states = [

    'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
    'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
    'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
    'Virginia', 'Washington', 'West Virginia', 'Wisconsin',    'Wyoming', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware',
    'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
    'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
  ].sort();

Upvotes: 1

Related Questions