【问题标题】:How do you move table row to the top in Angular ngFor loop?如何在 Angular ngFor 循环中将表格行移动到顶部?
【发布时间】:2021-01-30 06:54:38
【问题描述】:

使用 Angular 9,我正在遍历一个数据列表,但如果一个值等于 primary,我想将该特定行放在列表的顶部或第一个。

我的表已经在工作,我正在使用*ngFor="let item of items | sort: sortColumn: sortAscending 循环。但是,我在前端努力寻找使用 item.primary = true 的主节点并使其首先进入循环,然后继续循环。

我的 Angular 技能在这里受到限制。我已经看到unshift() 可以工作的答案,但我不确定如何将其编码为*ngFor

注意:这是标准的<table/> 表,不使用<mat-table/>

希望这是有道理的。谢谢!

【问题讨论】:

  • 也许您可以在将数据提供给ngFor 之前对其进行“预处理”。然后unshift 可能会出现在开头移动所需的行。

标签: javascript angular sorting ngfor


【解决方案1】:

您可以创建一个管道,使您的元素位于数组的开头。
首先你创建你的管道:

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: "primary" })
export class PrimaryPipe implements PipeTransform {
  transform(value: any[]): any[] {
    // get index of primary element
    const index = value.findIndex(el => el.primary);
    // get the element itself
    const primaryElement = value[index];
    // remove the element from the array
    value.splice(index, 1);
    // put the element at the start of the array
    value.unshift(primaryElement);
    / return the new arrary
    return value;
  }
}

在声明中将新管道添加到应用模块。
现在你可以在你的组件中使用这个管道了:

*ngFor="let item of items | sort: sortColumn: sortAscending | primary

这里有一个现场演示可以帮助您:link
在现场演示中查看以下文件:

  • primary.pipe.ts
  • primary-pipe.component.ts

查看html页面底部的预览

【讨论】:

  • 工作就像一个魅力。插入代码没有问题。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2019-10-08
  • 2018-04-10
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多