如何将 table 行移动到 Angular ngFor 循环的顶部?
How do you move table row to the top in Angular ngFor loop?
使用 Angular 9,我正在遍历数据列表,但如果值等于 primary
,我想将该特定行放在列表的顶部或第一位。
我已经让 table 工作了,我正在循环使用 *ngFor="let item of items | sort: sortColumn: sortAscending
。但是,我在前端努力寻找使用 item.primary = true
的主节点并使其首先进入循环,然后继续循环。
我的 Angular 技能在这里有限。我已经看到 unshift()
会起作用的答案,但我不确定如何将其编码为 *ngFor
.
注意:这是标准 <table/>
table,不使用 <mat-table/>
。
希望这是有道理的。谢谢!
您可以创建一个管道,使您的元素位于数组的开头。
首先创建管道:
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 页面底部的预览
使用 Angular 9,我正在遍历数据列表,但如果值等于 primary
,我想将该特定行放在列表的顶部或第一位。
我已经让 table 工作了,我正在循环使用 *ngFor="let item of items | sort: sortColumn: sortAscending
。但是,我在前端努力寻找使用 item.primary = true
的主节点并使其首先进入循环,然后继续循环。
我的 Angular 技能在这里有限。我已经看到 unshift()
会起作用的答案,但我不确定如何将其编码为 *ngFor
.
注意:这是标准 <table/>
table,不使用 <mat-table/>
。
希望这是有道理的。谢谢!
您可以创建一个管道,使您的元素位于数组的开头。
首先创建管道:
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 页面底部的预览