Search code examples
angularionic-frameworkangular-standalone-components

How to add ion-item to the ion-list in custom order?


I have a batches of items that are received as user perform ion-infinite-scroll. What I want is to be able to add ion-list items upward rather than downward. I tried Ionic 2 how to make ion-list grow from bottom upwards? and few others but not working. I am open to using other ionic components to achieve the same effect.

Simply reversing the items in the list before displaying doesn't work as each of item is arrays which is already rendered. In below example, say [1, 2, 3] each of which are array of items received at different times and rendered in ion-list in the order received. so in this example, 1 is received first, 3 is received at later time.

For example given following: [1, 2, 3] where 3 is the most recent data.
Ion list will display them as below where most recent element :

[1] <--- first insert
[2] <--- second insert
[3] <--- last insert

If I want to say add one more element to the list, the list becomes [1, 2, 3, 4] and [4] will be displayed after [3]

[1] <--- first insert
[2] <--- second insert
[3] 
[4] <--- last insert

I want to be able to append the item to the list so that the first insertion is at the bottom and second one stacked on the first, and so one, so above should be:

[4] <--- last insert
[3] 
[2] <--- second insert
[1] <--- fiirst insert

how can I achieve this?


Solution

  • This is more of a general js question than ionic. To add an item to the start of an array you use the javascript method unshift().

    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.unshift("Lemon");
    
    ex console: 'Lemon,Banana,Orange,Apple,Mango'
    

    Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift