当用户搜索时,他们会得到搜索中包含的项目列表,我无法弄清楚如何首先将其与包含最低数量的项目进行排序。示例我搜索"土豆","韭菜"我返回了包含此内容的所有项目,但第一项可能包括 15 项和接下来的 5 项,我希望首先列出最低的。
我有一个离子列表如下:
<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>
我需要根据以下条件对整个列表进行排序
项目.成分.长度
默认从低到高排序。
你不能使用pipe对它们进行排序,因为*ngFor
你只能访问一个元素而不是所有元素进行排序,那么你应该对ts文件中的整个数组进行排序,然后迭代它:
recipes.sort(function(a,b){
return a.ingredients.length - b.ingredients.length;
});
我猜你的recipes
数组来自服务。在您的配方服务中,您可以对该数组进行排序。
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;
});
}
}
或类似的东西...