簡體   English   中英

如何根據另一個數組訂購 ngFor 輸出?

[英]How can I order ngFor output based on another array?

我有一個數據,其中包括 8-20 和 20-8 的 2 個班次的輸出。 所以我已經使用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

答案是創建一個自定義管道。 感謝阿米爾的建議。

@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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM