首页 文章

订购从低到高的列表 - 离子

提问于
浏览
-1

当用户搜索他们获得搜索中包含的项目列表时,我无法确定如何从包含最低金额的项目中对其进行排序 . 示例我搜索“马铃薯”,“韭菜”我返回包含此项的所有项目,但第一项可能包括15和下一项5,我希望首先列出最低项目 .

我有一个Ion-list如下:

<ion-list>
  <ion-item *ngFor="let item of recipes" (click)="goToDetails(item.id)">
    <div class="thumb">
      <img src="{{item.smallImageUrls}}">
    </div>
    <div class="item-text">
      <div class="inner">
        <div class="title">
          <h1>{{item.recipeName}}</h1>
        </div>
        <div class="rating">
          <rating [(ngModel)]="item.rating"></rating>
        </div>
        <div class="time">
          <p>{{item.totalTimeInSeconds | HoursMinutesSeconds}} minutes</p>
        </div>
        <div class="ingredients">
          <p>{{item.ingredients.length}} Ingredients</p>
        </div>
      </div>
    </div>
  </ion-item>
</ion-list>

我需要根据整个列表排序

item.ingredients.length

默认情况下从低到高排序 .

2 回答

  • 3

    你不能使用管道来对它们进行排序,因为在 *ngFor 中你只能访问一个元素而不是所有它们进行排序,那么你应该在ts文件中对整个数组进行排序然后迭代它:

    recipes.sort(function(a,b){
      return a.ingredients.length - b.ingredients.length; 
    });
    
  • 0

    我想你的 recipes 数组来自一个服务 . 在RecipeService中,您可以对该数组进行排序 .

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    ...
    @Injectable()
    export class RecipeService {
      ...
      constructor(private http: HttpClient) { }
    
      getRecipes(): Observable<Recipe> {
        return this.http
          .get<Recipe[]>(`${url}`)
          .pipe(map(recipes: Array<Recipe>) => this.sortArray(recipes)), this.catchHttpErrors());
      }
      ...
      sortArray(arr: Array<Recipe>) {
        return arr.sort((a: Recipe, b: Recipe) => {
          if (a.ingredients.length < b.ingredients.length) {
            return -1;
          } else if (a.ingredients.length > b.ingredients.length) {
            return 1;
          }
          return 0;
        });
      }
    }
    

    或类似的东西......

相关问题