3

I have created array in my ts file and with ngFor get elements from array, but when I use key value angular is automatically sorting the array. How to save the order like array was created.

TS code:

filterListingTypeItems: { [key: string]: object } = {


  'For sale': [
      'For sale',
      'By Agent',
      'By ownre',
      'New Construction',
      'Foreclosures',
      'Coming Soon',
    ],
    'Potential listings': [
      'Potential listings',
      'Foreclosed',
      'Pre-Foreclosure',
      'Make Me Move',
    ],
    'For Rent': ['For Rent'],
    'Recently sold': ['Recently sold'],
    _________________________: ['Open House only', 'Pending & Under Contract'],
}

HTML code (angular material):

<mat-optgroup
          *ngFor="let listingOptions of (filterListingTypeItems | keyvalue)"
          [label]="listingOptions.key"
        >
          <mat-option
            *ngFor="let listingOption of listingOptions.value"
            [value]="listingOption"
            >{{ listingOption }}</mat-option
          >
</mat-optgroup>

it becomes like that (img)

EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
Ilyoskhuja
  • 146
  • 3
  • 14
  • Possible duplicate of [angular keyvalue pipe sort properties / iterate in order](https://stackoverflow.com/questions/52793944/angular-keyvalue-pipe-sort-properties-iterate-in-order) – Just code Dec 21 '18 at 10:58

2 Answers2

7

you can create a function that returns 0 in the component ts file.

function returnZero() {
return 0
}

Inside the template file

<td *ngFor="let item of cfValues | keyvalue : returnZero">
Kanish Mathew
  • 825
  • 10
  • 6
1

You did not create an array but an object. So there is no order in the first place.

If you need an order, make an array instead of object.

filterListingTypeItems = [
  {
    key: 'For sale',
    value: [
      'For sale',
      'By Agent',
      'By ownre',
      'New Construction',
      'Foreclosures',
      'Coming Soon',
    ]
  },
  ...
]
zmag
  • 7,825
  • 12
  • 32
  • 42