用* ngFor数组排序 [英] Orderby with *ngFor array

查看:408
本文介绍了用* ngFor数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Firebase实时数据库在json文件中制作了以下结构,以处理Composer及其组合:

I made the following structure in my json file with Firebase Real Time Database to work on Composer and his Compositions:

我提供以下服务,向我提供一位作曲家的数据及其构图

I have the following service that give me the data of one composer with his composition

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指令获取有关他的作曲列表的作曲家信息:

Now I can get the composer info with a list of his compositions with the ngFor directive :

<mat-list-item *ngFor="let composition of composer.arrcompositions">
    {{ composition[1] }}
</mat-list-item>

我的问题是我无法按字母顺序对作品进行排序.我尝试使用 ngx-order-pipe ,但我不知道如何精确确定用于订购的值

My problem is that I can't order the compositions in alphabetic order. I tried to use the ngx-order-pipe but I don't know how to precise the value used to order

<mat-list-item *ngFor="let composition of composer.arrcompositions | orderBy: 'composition[1]'">
{{ composition[1] }}

这显然行不通...

推荐答案

You should not use ordering pipes.

Angular团队和许多经验丰富的Angular开发人员强烈建议将逻辑过滤和排序到组件中.

The Angular team and many experienced Angular developers strongly recommend moving to filter and sorting logic into the component.

如果要对项目进行排序,例如name,它就可以了:

If you want to sort your items by, let's say, name, here it goes :

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>

这篇关于用* ngFor数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆