如何基于另一个数组订购ngFor输出?

时间:2019-06-14 13:16:21

标签: angular typescript

我有一个数据,其中包含2个班次的输出(柔和8-20和20-8)。 因此,我现在使用ngx-pipes过滤了输出,现在我需要订购夜班时间,从晚上20点到早上7点。

我有一个数组,用于指定小时数的正确顺序。

shiftSelection = [
{
  name: "Day Shift",
  hours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
},
{
  name: "Night Shift",
  hours: [20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7]
}]

data = [
    {
      "lineId": 1,
      "hour": 0,
      "input": 9136,
      "output": 8850
    }, 
    ... 
    {
      "lineId": 1,
      "hour": 23,
      "input": 9136,
      "output": 8850,
    }]

如何基于另一个数组订购ngFor输出?

<div *ngFor="let row of data | filterBy: ['hour']: currShift.hours :1 | groupBy: 'lineId' | pairs">
    <span class="group-title">Line {{row[0]}}</span>
    <ng-container *ngFor="let cell of row[1]"> 
        <span class="cell" matTooltip="{{cell | json}}">{{cell.output}} 
        </span>
    </ng-container>
</div>

像这样的东西会很完美:

*ngFor="let cell of row[1] | orderBy: currShift"

https://stackblitz.com/edit/angular-lckecp

1 个答案:

答案 0 :(得分:1)

答案是创建一个自定义管道。感谢阿米尔的建议。

@Pipe({ name: 'orderByArray' })
export class OrderByArrayPipe implements PipeTransform {

    transform(array: Array<Cell>, orderByArray: Array<number>): Array<Cell> {

   var orderedArray = array.slice().sort(function (a, b) {
     return orderByArray.indexOf(a.hour) - orderByArray.indexOf(b.hour);
   });

   return orderedArray;
   }
}

并以这种方式使用它:

<ng-container *ngFor="let cell of row[1] | orderByArray: currShift.hours">