0

I make a list of item in angular 2 .I want to sort that list using custom fliter or using pipe .can we sort my list with lastname .I tried like this

<ul *ngFor="let user of userList | lastname" class="userlist">
  <li>
    <span>{{user.name}}</span>
    <span>{{user.lastname}}</span>
    <span>{{user.age}}</span>
  </li>
</ul>

but it gives me error so reverted please suggest a way to sort that https://stackblitz.com/edit/angular-fdxser?file=src%2Fapp%2Fapp.component.html

user944513
  • 12,247
  • 49
  • 168
  • 318

3 Answers3

4

Here is how the Pipe should look (from your link)

lastname.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'lastname'
})
export class LastnamePipe implements PipeTransform {

  transform(values: any[]): any[] {
    return values.sort((a, b) => a.lastname.localeCompare(b.lastname));
  }
}

if you want it the other way arround add a .reverse(); to the return statements or do b.lastname.localeCompare(a.lastname)

Tobias Fuchs
  • 910
  • 5
  • 8
0

Add following sort pipe in your project. The following pipe is generic, you can change the attribute to sort as well ex. sort.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: "sortBy"})
export class SortPipe implements PipeTransform {

    transform(array: Array<any>, args: any): Array<any> {
        console.log("arra", array, '-- args:', args);
        if (array !== undefined) {
            let keys, order;
            if(typeof args == 'string'){ // use default sort criteria
                keys = [args];
                order = 1;
            }

            if(keys.length > 0){
                array.sort((a: any, b: any) => {
                    if (a[keys[0]] < b[keys[0]]) {
                        return -1 * order;
                    } else if (a[keys[0]] > b[keys[0]]) {
                        return 1 * order;
                    } else {
                        return 0;
                    }
                });
            }
        }
        return array;
    }
}


Declare s rot pipe in pipeModule like: pipes.module.ts

import {NgModule} from '@angular/core';
import {SortPipe} from './sort.pipe';

@NgModule({
    imports: [],
    declarations: [SortPipe],
    exports: [SortPipe],
})

export class PipesModule {
    static forRoot() {
        return {
            ngModule: PipesModule,
            providers: [],
        };
    }
}

Inject PipeModule in app.module.ts. And HTML will be:

<ul *ngFor="let user of userList | sortBy :'lastname'" class="userlist">
Pradnya Sinalkar
  • 1,116
  • 4
  • 12
  • 26
0

You would need to write a custom pipe for that.

Check out this answer from Cory Shaw - angular-2-sort-and-filter

Community
  • 1
  • 1