'How to use .slice().reverse() in *ngFor with | keyvalue?
I often use .slice().reverse() in *ngFor to display elements in reverse order. But now I have a problem, because I also use | keyvalue. How to use .slice().reverse() with | keyvalue?
<div *ngFor="let order of orderData.order.slice().reverse() | keyvalue ">
Sum: {{order.value.sum}}
</div>
Solution 1:[1]
I don't think that you issue is with the keyvalue
pipe. Probably the orderData
is still not loaded whenever you are trying to use it and order
is undefined.
You can do optional chaining/safe navigation operator in templates and adding a ? checks to see if the item on the left side has this property and and if it does it just returns it, if it doesn't it returns undefined and in this case if order is undefined inside the pipe transform method as value you will get undefined
and if it exists you will get your array.
<div *ngFor="let order of orderData.order?.slice()?.reverse() | keyvalue ">
Sum: {{order.value.sum}}
</div>
Or you can just check if orderData has the order array and then render using the ngIf directive.
I suggest that you don't do slice().reverse()
inside the templates like this because on every change detection cycle you will be creating a new array and reversing it. It would be a good idea to create a new pure pipe called reverse that reverses the array only if the instance has changed because otherwise you might get in trouble when working with larger arrays. Also if you are working with larger arrays providing a TrackByFunction on the ngFor will also increase performance.
Solution 2:[2]
I think the problem is here orderData.order
, is undefined. That's why it throwing that error. You can make sure orderData.order
is present then iterate the list like the below.
Note: ng-container
is just a wrapper and Angular doesn't put it in the DOM.
<ng-container *ngIf="orderData.order">
<div *ngFor="let order of orderData.order.slice().reverse() | keyvalue">
Sum: {{order.value.sum}}
</div>
</ng-container>
Solution 3:[3]
We can get the last entries of the array by specifying the number inside slice with reverse function.
<div *ngFor="let order of orderData.order?.slice(-10)?.reverse() | keyvalue ">
Sum: {{order.value.sum}}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Naren |
Solution 3 | Surya R Praveen |