【问题标题】:Incorrect Array Sorting in Angular 6Angular 6中的数组排序不正确
【发布时间】:2019-08-02 18:29:33
【问题描述】:

我正在使用 *ngFor 来迭代数据表中的对象数组和序列号。我使用let index of i,然后将其打印到桌子上,但我面临的问题是在第 9 个序列号之后。我有 10 个,但在 1 个序列号之后。像 1, 10, 11, 2, 3。有人可以帮我吗? 这是我的打字稿代码和 html 代码。

// GETTING BONUS DATA
 getAllJobposts() {
 this.apiService.hrService.getAllJobPost().subscribe((res: any) => {
  this.jobPostsData = res.data;
  console.log(this.jobPostsData);
  // this.DataTablesFunctionCallAfterDataInit()
 });
}

 <tr class="MousePointer" (click)="EditRecord(post.id, target)" *ngFor="let 
   post of jobPostsData | reverse; let i = index">

              <td>{{ i+1 }}</td>
              <td>
                <span style="display: inline">
                  <a class=" btn btn-link btn-sm " title="Delete" [id]="post.id" (click)="$event.stopPropagation();modal.ShowModal(post.id)">
                    <i [ngStyle]="{color: 'blue'}" class="fa fa-trash-o ">
                    </i>
                  </a>
                  <a class="btn btn-link btn-sm btn-round" title="Edit" (click)="$event.stopPropagation();EditRecord(post.id,target)">
                    <i [ngStyle]="{color: 'blue'}" class="fa fa-pencil-square-o "></i>
                  </a>
                </span>
              </td>
              <td>{{ post.jobTitle }}</td>
              <td>{{ getDepartmentName(post.departmentId) }}</td>
              <td>{{ getDesignationName(post.designationId) }}</td>
              <td>{{ post.totalPosition }}</td>
              <td>{{ post.minExperience }}</td>
              <td>{{ getCityName(post.cityId) }}</td>
              <td>
                <span [class]="post.active == 1? 'status success':'status danger'" style="width:60px !important; text-align: center;">
                  {{post.active == 1? "Active":"In-Active" }}
                </span>
              </td>
            </tr>

【问题讨论】:

  • 请发布 stackblitz
  • 显示您的reverse 管道。
  • 好吧,我试过没有反向管道。但结果相同
  • @AbdulBasit 这个项目真的很大,所以我不能把它发布到 stackblitz...
  • 看起来它正在将您的列排序为字符串而不是数字。如果不查看其余代码,很难确切地说出问题所在。你用的是什么表格元素?

标签: angular html-table ngfor httpservice


【解决方案1】:

看来你需要用这样的方式重写你的 reverse 管道:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value) {
    return value.sort((a, b) => {
      return (b.id - a.id);
    }); 
  }
}

在排序函数中,您需要指定对象字段进行排序: return (b.id - a.id).

如果 id 是字符串,则使用 parseInt(b.id) - parseInt(a.id)(否则它将输出与屏幕截图相同的结果,即按字母顺序)

此外,您可以通过parameters of pipe 传递对象字段进行排序

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多