[英]FIlter array of data with dropdown without pipe Angular?
I need to filter data by selected dropdown item.我需要按选定的下拉项过滤数据。 It currently searches me only once when I select filters and after that it is always empty.
当我选择过滤器时,它目前只搜索我一次,之后它始终为空。 Example:
例子:
<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')
// }
} }
He does it only once again.他只会再做一次。 The next time I try to select a dropdown value it returns an empty array.
下次我尝试选择下拉值时,它会返回一个空数组。
Don't filter
the array directly, because you will lose all items in the array that do not meet the filter
criteria.不要直接
filter
数组,因为你会丢失数组中所有不符合filter
条件的项目。
Instead, hold the items in another variable and use that one to filter相反,将项目保存在另一个变量中并使用该变量进行过滤
allItems = [...this.meals];
// [...]
this.meals = allItems.filter(() => {});
Because you're updating your meals
data so that the other cases might not work as intended.因为您正在更新您的
meals
数据,因此其他情况可能无法按预期工作。 You need to assign your meals
data with another variable like您需要为您的
meals
数据分配另一个变量,例如
....subscribe(res) => {
// here you need to assign in two different variables
this.allMeals = res;
this.meals = res;
}
Then in your cases instead of filtering from meals
, you need to filter from this.allMeals
and assign result to meals
variable.然后在你的情况下,而不是从过滤
meals
,你需要从过滤器this.allMeals
和分配结果meals
变量。
case '2':
this.meals = this.allMeals.filter(meal => meal.trainerId == '2')
break;
In this case your meals
will have a filtered result from allMeals
every time.在这种情况下,您的
meals
每次都会从allMeals
得到过滤结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.