【问题标题】:FIlter array of data with dropdown without pipe Angular?过滤没有管道角的下拉数据数组?
【发布时间】:2020-10-20 21:37:04
【问题描述】:

我需要按选定的下拉项过滤数据。 它目前仅在我选择过滤器时搜索我一次,之后它始终为空。 示例:

        <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')  
// }

}

他只做了一次。下次我尝试选择一个下拉值时,它会返回一个空数组。

【问题讨论】:

  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: javascript html angular drop-down-menu


【解决方案1】:

因为您正在更新您的 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 的过滤结果。

【讨论】:

    【解决方案2】:

    不要直接filter数组,因为你会丢失数组中所有不符合filter条件的项。

    相反,将项目保存在另一个变量中并使用该变量进行过滤

    allItems = [...this.meals];
    // [...]
    this.meals = allItems.filter(() => {});
    

    Playground example

    【讨论】:

    • 嗯,我会按照你的方式做,但情况相同。相同的。让 allMealsClone = [...this.meals] 和 this.meals = allMealsClone.filter(meal => meals.trainerId == '0')
    • @pekamap9 它正在工作,请检查添加的示例。如果您的问题仍然存在,请考虑制作一个可重现的示例来显示问题。
    猜你喜欢
    • 2021-04-06
    • 2018-05-09
    • 1970-01-01
    • 2021-10-29
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2012-03-25
    相关资源
    最近更新 更多