如何通过属性对对象进行数组排序使用ngFor

时间:2019-05-14 08:16:23

标签: javascript angular sorting ngfor

我不希望在表中显示排序数据

js

let array = [
{idx: number, name: string, btn: number, index: number},
{idx: number, name: string, btn: number, index: number},
{idx: number, name: string, btn: number, index: number}
]

html

<tr *ngFor="let ticket of array">
<td>{{ticket.name}}</td>
<td>{{ticket.btn}}</td>
<td>{{ticket.index}}</td>
<tr>

我需要按索引值排序显示

4 个答案:

答案 0 :(得分:1)

let array = [
  { idx: 1, name: 'a', btn: 1, index: 2 },
  { idx: 2, name: 'b', btn: 2, index: 3 },
  { idx: 3, name: 'c', btn: 3, index: 1 }
];

// descending
let newarr = array.sort((a, b) => b.index - a.index);

//ascending
let newarr = array.sort((a, b) => a.index - b.index);

console.log(newarr);

答案 1 :(得分:1)

您可以只使用排序数组:

function sortFunc(a, b) {
  if ( a.index < b.index ){
    return -1;
  }
  if ( a.index > b.index ){
    return 1;
  }
  return 0;
}

let array = [
  {idx: number, name: string, btn: number, index: number},
  {idx: number, name: string, btn: number, index: number},
  {idx: number, name: string, btn: number, index: number}
].sort(sortFunc);

或者您可以使用lodash orderBy https://lodash.com/docs/4.17.11#orderBy

答案 2 :(得分:0)

这里是OrderBy管道库。
 https://github.com/VadimDez/ngx-order-pipe

 npm install ngx-order-pipe --save

答案 3 :(得分:0)

您应该使用管道对显示在视图之前的数据进行排序:

public int GetColumnMaxLength(EntityEntry entityEntry)
{
    int result = 0;

    var table = entityEntry.Metadata.Model.FindEntityType(entityEntry.Metadata.ClrType);

    // Column info 
    foreach (var property in table.GetProperties())
    {
        var maxLength = property.GetMaxLength();

        // For sql info, e.g. ColumnType = nvarchar(255):
        var sqlInfo = property.SqlServer();
    };
    return result;
}

在排序管道中,您可以使用:

<tr *ngFor="let ticket of array|sort-pipe">
   <td>{{ticket.name}}</td>
   <td>{{ticket.btn}}</td>
   <td>{{ticket.index}}</td>
<tr>