使用 *ngFor 数组的 Orderby
Orderby with *ngFor array
我在我的 json 文件中使用 Firebase 实时数据库创建了以下结构,以处理 Composer 及其组合:
我有以下服务,可以为我提供一位作曲家的数据以及他的作曲
getComposerWithKey(key: string): Observable<Composer> {
const memberPath = `composer/${key}`;
this.composer = this.db.object(memberPath)
.snapshotChanges().map(action => {
const $key = action.payload.key;
const arrcompositions = action.payload.val().compositions?Object.entries(action.payload.val().compositions):null;
const data = {
$key,
arrcompositions,
...action.payload.val() };
return data;
});
return this.composer
}
现在我可以使用 ngFor 指令获取作曲家信息以及他的作品列表:
<mat-list-item *ngFor="let composition of composer.arrcompositions">
{{ composition[1] }}
</mat-list-item>
我的问题是我无法按字母顺序排列作文。我尝试使用 ngx-order-pipe 但我不知道如何精确用于订购的值
<mat-list-item *ngFor="let composition of composer.arrcompositions | orderBy: 'composition[1]'">
{{ composition[1] }}
这显然行不通...
You should not use ordering pipes。
The Angular team and many experienced Angular developers strongly recommend moving to filter and sorting logic into the component.
如果您想按照 name
对您的项目进行排序,那就是:
sortBy(prop: string) {
return this.composer.arrcompositions.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
}
在你的 HTML 中:
<mat-list-item *ngFor="let composition of sortBy('name')">
{{ composition[1] }}
</mat-list-item>
我使用这个包:ngx-pipes.
- npm i ngx-pipes
import {NgPipesModule} from 'ngx-pipes';
@NgModule({
// ...
imports: [
// ...
NgPipesModule
]
})
<div *ngFor="let item of items | orderBy: 'id'"> {{ item }} </div>
我在我的 json 文件中使用 Firebase 实时数据库创建了以下结构,以处理 Composer 及其组合:
我有以下服务,可以为我提供一位作曲家的数据以及他的作曲
getComposerWithKey(key: string): Observable<Composer> {
const memberPath = `composer/${key}`;
this.composer = this.db.object(memberPath)
.snapshotChanges().map(action => {
const $key = action.payload.key;
const arrcompositions = action.payload.val().compositions?Object.entries(action.payload.val().compositions):null;
const data = {
$key,
arrcompositions,
...action.payload.val() };
return data;
});
return this.composer
}
现在我可以使用 ngFor 指令获取作曲家信息以及他的作品列表:
<mat-list-item *ngFor="let composition of composer.arrcompositions">
{{ composition[1] }}
</mat-list-item>
我的问题是我无法按字母顺序排列作文。我尝试使用 ngx-order-pipe 但我不知道如何精确用于订购的值
<mat-list-item *ngFor="let composition of composer.arrcompositions | orderBy: 'composition[1]'">
{{ composition[1] }}
这显然行不通...
You should not use ordering pipes。
The Angular team and many experienced Angular developers strongly recommend moving to filter and sorting logic into the component.
如果您想按照 name
对您的项目进行排序,那就是:
sortBy(prop: string) {
return this.composer.arrcompositions.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
}
在你的 HTML 中:
<mat-list-item *ngFor="let composition of sortBy('name')">
{{ composition[1] }}
</mat-list-item>
我使用这个包:ngx-pipes.
- npm i ngx-pipes
import {NgPipesModule} from 'ngx-pipes';
@NgModule({
// ...
imports: [
// ...
NgPipesModule
]
})
<div *ngFor="let item of items | orderBy: 'id'"> {{ item }} </div>