首页 > 解决方案 > 在 Angular 9 中的 ngFor 中使用 *ngIf 时出现数组索引模式问题

问题描述

data=[
      {name:"Danger",color:"red",intensity:100},
      {name:"Success",color:"green",intensity:20},
      {name:"Warning",color:"yellow",intensity:70},
      {name:"cool",color:"blue",intensity:80}

     ]

<div *ngFor="let element of data;let i=index">
   <span *ngIf="element.intensity>50">
    {{i+1}} {{element.name}}
   </span>
</div>
Output:
1.Danger
3.Warning
4.cool
Desired Output
1.Danger
2.Warning
3.cool

在索引 2 中丢失,因为索引 2 处没有显示任何元素,但我希望输出作为我想要的输出。

非常感谢任何建议或帮助。

标签: angulartypescriptalgorithmdata-structures

解决方案


选项 1 - 在 @Component 中过滤

@Component

this.filteredData = this.data.filter(({ intensity }) => intensity > 50);

HTML

<div *ngFor="let element of filteredData; index as i">
  {{ i + 1 }} {{ element.name }}
</div>

选项 2 - 在 @Pipe 中过滤

@Pipe

@Pipe({
  name: 'filterByIntensity'
})
export class FilterByIntensityPipe implements PipeTransform {
  transform(value: any[]): any[] { // Put the correspondent interface here
    return value.filter(({ intensity }) => intensity > 50);
  }
}

HTML

<div *ngFor="let element of data | filterByIntensity; index as i">
  {{ i + 1 }} {{ element.name }}
</div>

请注意,这是一个非常具体的@Pipe. 我建议您创建更通用的东西,例如filterBy您可以在哪里传递要过滤的属性等,以及为什么不在其他地方重用它。


推荐阅读