【问题标题】:How can I order ngFor output based on another array?如何根据另一个数组订购 ngFor 输出?
【发布时间】:2019-06-14 23:29:44
【问题描述】:

我有一个数据,其中包括来自 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

【问题讨论】:

  • 如果您打开我创建的 StackBlitz 并将组合框更改为 Night Shift,顶行显示 20 -7 小时。我希望以与 currShift 变量相同的顺序对其余数据进行排序。如果您悬停任何单元格,您将看到对象详细信息,并且您会看到它从 0 变为 23。
  • 也许我理解错了,但是白天和晚上的小时数不一样。您要订购它们的数组在哪里?也许会大大降低示例的复杂性并将其显示为 StackBlitz?我愿意提供更多帮助。
  • 嗨 Ben,这实际上是简化版。两个班次的小时数相同 12。看看变量 shiftSelection,它确实包含两个对象 Day 和 Night shift。当您选择一个时,它将所选对象中的数组小时分配到 currShift 数组中。这是我要订购的数组。我遇到的问题是,如果我要订购夜班值,它会上升到 0、1、2、3、4、5、6、7、20、21、22、23,我希望在哪里订购20,21,22,23,0,1,2,3,4,5,6,7
  • 因此您需要将 1 个数组按另一个数组排序,我怀疑 ngx-pipes 是否可行,但您可以实现适合此目的的自己的管道。如果您需要任何帮助,请告诉我。
  • 我认为您需要创建一个引用数组来控制包含您的特定小时顺序的循环 night = [20,21,22,23,0,1,2,3,4,5,6,7] 在循环期间您可以引用索引以指向另一个数组的索引。跨度>

标签: angular typescript


【解决方案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">

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2010-09-07
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多