Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable the default keyvalue pipe sort in angular

<tr *ngFor="let a of arrayOfObjects">
    <td *ngFor="let item of cfValues | keyvalue">
        {{item.value}}
    </td>
</tr>

I am just trying to print the items in the regular order but the key/value pipe does a default sorting based on the index. Is there a way to disable the default sorting?

like image 513
Abdul K Shahid Avatar asked Jan 08 '19 11:01

Abdul K Shahid


People also ask

What is KeyValue pipe in angular?

KeyValuePipelinkTransforms Object or Map into an array of key value pairs. {{ input_expression | keyvalue [ : compareFn ] }}

What is KeyValue in ngFor?

The KeyValue Pipe converts given Object or Map into an array of key-value pairs. We can use this with the ngFor to loop through the object keys. The keyValue accepts the one argument compareFn , which we can use to set the custom sort to the pipe.

What is key in angular?

KeyValue pipe released in Angular 6.1 to loop through objects,Maps and arrays. Now by passing KeyValue pipe to *ngFor we can loop through objects key values & maps. Prior to this Angular 6.1 release we cannot iterate directly through objects key values & maps using *ngFor directive.


1 Answers

You need to return 0 if you want them to not be ordered. So in your cause you could either do <td *ngFor="let item of cfValues | keyvalue : 0">

But that would throw a ts error: TypeError: The comparison function must be either a function or undefined

Else, you can create a function that returns 0 and use

returnZero() {
    return 0
}

[... in your template]

<td *ngFor="let item of cfValues | keyvalue : returnZero">
like image 54
alberto montalesi Avatar answered Sep 18 '22 09:09

alberto montalesi