我需要按所选下拉项筛选数据。当我选择过滤器时,它目前只搜索我一次,之后它总是空的。示例:
<select class="select" (change)="onChangeMeal($event)">
<option value="Izaberit">Choice meal</option>
<option *ngFor="let meal of mealType" [value]="meal.num">
{{ meal.name }}
</option>
</select>
onChangeMeal(evt) {
let mealTypeNumber = evt.target.value;
console.log(mealTypeNumber);
switch (mealTypeNumber) {
case '0':
this.meals = this.meals.filter(meal => meal.trainerId == '0')
console.log('0 meal' , this.meals)
break;
case '1':
this.meals = this.meals.filter(meal => meal.trainerId == '1')
console.log('1 meal' , this.meals)
break;
case '2':
this.meals = this.meals.filter(meal => meal.trainerId == '2')
break;
case '3':
this.meals = this.meals.filter(meal => meal.trainerId == '3')
break;
default:
break;
}
// if(evt.target.value == '1') {
// console.log('jes')
// this.meals = this.meals.filter(meal => meal.trainerId == '1')
// }
// if(evt.target.value == '2') {
// console.log('jes 2')
// this.meals = this.meals.filter(meal => meal.trainerId == '2')
// }
}
他只做了一次。下次我尝试选择下拉值时,它会返回一个空数组。
因为您正在更新meals
数据,所以其他情况可能无法按预期工作。您需要将meals
数据分配给另一个变量,如
....subscribe(res) => {
// here you need to assign in two different variables
this.allMeals = res;
this.meals = res;
}
然后,在您的情况下,您需要从this.allMeals
进行筛选,并将结果分配给meals
变量,而不是从meals
进行筛选。
case '2':
this.meals = this.allMeals.filter(meal => meal.trainerId == '2')
break;
在这种情况下,您的meals
每次都会有一个来自allMeals
的过滤结果。
不要直接filter
数组,因为您将丢失数组中所有不符合filter
条件的项。
相反,将项目保存在另一个变量中,并使用该变量来过滤
allItems = [...this.meals];
// [...]
this.meals = allItems.filter(() => {});
游乐场示例