Javascript Orderby 与 *ngFor 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48403154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:06:03  来源:igfitidea点击:

Orderby with *ngFor array

javascriptangularfirebase-realtime-databasengfor

提问by C. Banzet

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

我使用 Firebase 实时数据库在我的 json 文件中创建了以下结构来处理 Composer 和他的作品:

enter image description here

enter image description here

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
}

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

现在我可以使用 ngFor 指令获取作曲家信息以及他的作品列表:

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

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

我的问题是我不能按字母顺序排列作品。我尝试使用ngx-order-pipe但我不知道如何精确用于订购的值

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

This obviously doesn't work...

这显然行不通...

回答by

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.

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

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

如果你想对你的项目进行排序,比方说name,这里是:

sortBy(prop: string) {
  return this.composer.arrcompositions.sort((a, b) => a[prop] > b[prop] ? 1 : a[prop] === b[prop] ? 0 : -1);
}

In your HTML :

在您的 HTML 中:

<mat-list-item *ngFor="let composition of sortBy('name')">
  {{ composition[1] }}
</mat-list-item>