Custom pipe doesn't work properly in Angular2

680 Views Asked by At

The pipe has to sort an array of objects by the name property.

sort-by.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
  private name: string;

  transform(array: Array<any>, args: string[]): Array<any> {
    array.sort((a: any, b: any) => {
      if (a.name < b.name) {
        return -1;
      } else if (a.name > b.name) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}

app.component.html:

 <table>
    <tr *ngFor="let elem of _values | sortBy">
      <td>{{ elem.name }}</td>
      <td>{{ elem.ts }}</td>
      <td>{{ elem.value }}</td>
    </tr>
  </table>

app.module.ts:

//other imports
import { SortByPipe } from './sort-by.pipe';

@NgModule({
  declarations: [
    SortByPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: []
})
export class AppModule { }

The array of objects:

[{
  "name": "t10",
  "ts": 1476778297100,
  "value": "32.339264",
  "xid": "DP_049908"
}, {
  "name": "t17",
  "ts": 1476778341100,
  "value": "true",
  "xid": "DP_693259"
}, {
  "name": "t16",
  "ts": 1476778341100,
  "value": "true",
  "xid": "DP_891890"
}];

It doesn't sort the objects properly, but also doesn't throw any errors.
Maybe there's something wrong with my files?

Any help appreciated!

2

There are 2 best solutions below

0
On

Have you tried adding pure: false?

This makes it so that Angular doesn't care if the input is changed or not

@Pipe({
  name: "sort",
  pure: false
})
5
On

The problem is that you are piping the elements and not the array itself.

You should change this

<tr *ngFor="let elem of _values | sortBy">

to this:

<tr *ngFor="let elem of (_values | sortBy)">