Search code examples
javascriptangularjsangularangular-filtersangular2-pipe

angular 2 pipe for track number


I have json like this :

[
{
 id : 4
},
{
 id : 3
},
{
 id : 2
},
{
 id : 1
}
]

I want in *ngFor create a pipe that my template get like this after get rendered (list From small to large According to id)

<span><span><=== id =1
<span><span><=== id =2
<span><span><=== id =3
<span><span><=== id =4

angular 2 have PIPE for this work? or We must create a pipe like this?(HOW)


Solution

  • You'll need a simple sorting pipe. Of course you could make it more general, too:

    @Pipe({
        name: 'sortById',
        pure: true
    })
    export class IdSortPipe implements PipeTransform {
    
        transform(value: Array<any>, args:any[]):any {
            value.sort((a, b) => {
                return a.id - b.id;
            });
    
            return value;
        }
    }
    

    In your template:

    <span *ngFor="let obj of array | sortById">id = {{obj.id}}</span>
    

    Plunker for example usage