是否有另一种方法来访问* ngFor项而不是其索引

时间:2016-12-24 00:28:00

标签: angular typescript ngfor

我有一个*ngFor食物项目列表(foods),当用户将鼠标悬停在元素上时会执行动画

<div [@foodState]="food.state" *ngFor="let food of foods; trackBy let i=index" (mouseenter)="open(i)" (mouseleave)="close(i)">

open()close()方法会更改名为state的元素上的属性

open(i: number): void{
  this.foods[i].state = 'open';
}

触发新的动画状态

animations: [
  trigger('foodState', [
    state('closed', style({
      height: '36px'
    })),
    state('open', style({
      height: '58px'
    })),
  ])
]

我遇到的问题是我想添加@Pipe来根据搜索字词过滤数据:

<div [@foodState]="food.state" *ngFor="let food of foods| searchPipe: searchTerm; trackBy let i=index" (mouseenter)="open(i)" (mouseleave)="close(i)">

@Pipe使用foods函数转换filter()列表:

transform(foods: any[], searchTerm: string): any[] {
  foods = foods.filter(food => food.name.toUpperCase().indexOf(searchTerm.toUpperCase()) !== -1 );
  return foods;
}

所以现在用户将悬停的食物索引不再对应foods列表中的正确食物。

有没有办法触发重复项的状态而不通过原始数组索引访问它?或者我是否应该采用另一种方式来访问*ngFor列表中的数据?

1 个答案:

答案 0 :(得分:4)

您可以传递食物本身而不仅仅是索引:

 <div [@foodState]="food.state" *ngFor="let food of foods; trackBy let i=index" (mouseenter)="open(food)" (mouseleave)="close(food)">

并更改打开和关闭方法:

open(food: any): void{
  food.state = 'open';
}