angular - 在 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 处没有显示任何元素,但我希望输出作为我想要的输出。
非常感谢任何建议或帮助。
解决方案
选项 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
您可以在哪里传递要过滤的属性等,以及为什么不在其他地方重用它。
推荐阅读
- java - 如何将多个 API 方法的参数传递给 ViewModel
- java - 对象实例化如何用于接口
- sql - laravel 8:使用唯一验证更新用户电子邮件引发错误
- sql-server - 要安装什么程序来将 Visual Studio 与 SQL Server 数据库文件 (SqlClient) 连接起来?
- java - How to fill a HashMap from another HashMap using streams
- unix - 提取两个符号之间的字符串
- sql - SQL 比较行
- xamarin.forms - 从 sqlite Foxit SDK FullTextSearch 检索结果
- javascript - 如何创建几个月内进行的分析总数的图表?
- html - 如何在元素桌面和移动虚拟机之间建立连接线?