Angular2 Sorting Pipe with Object Array

后端 未结 3 1745
余生分开走
余生分开走 2021-01-14 05:01

How to make a sorting pipe in angular2 with an array of objects

Original Problem:

I have a TODOs list, (Todo[ ]) and I want to sort it every time I make

相关标签:
3条回答
  • 2021-01-14 05:33

    You need to change your html template so that your pipe can accommodate your async code.

    Change this line:

    <li *ngFor="#todo of todos | sort; #i=index">
       (...)
    </li>
    

    To this:

    <li *ngFor="#todo of todos | async | sort; #i=index">
       (...)
    </li>
    

    I copied your Pipe code into this Plunker:

    https://plnkr.co/edit/RBpZilgxIyRDLwktNZN1?p=preview

    0 讨论(0)
  • 2021-01-14 05:34

    Perhaps the value todos is null at the beginning because it's loaded asynchronously using HTTP.

    To prevent from such use case you could add this in your pipe:

    @Pipe({
      name: "sort"
    })
    export class TodosSortPipe implements PipeTransform {
      transform(array: Todo[], args: any): Todo[] {
        if (array == null) {
          return null;
        }
        (...)
      }
    }
    

    Then the value todos will be received and the transform method of the pipe will be called again with this non null value...

    Moreover it seems that your <li> tag isn't ended. You must have valid HTML into component templates. I don't know if it's the complete code or a truncated one...

    Hope it helps you, Thierry

    0 讨论(0)
  • 2021-01-14 05:44

    I've created an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.

    <li *ngFor="#todo of todos | orderBy : ['completed']; #i=index">
        {{i}}) {{todo.name}} - {{todo.completed}}
    </li>
    

    This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items dynamically.

    I have a write up on the process here.

    And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

    0 讨论(0)
提交回复
热议问题