javascript - ngFor 只是设置最后一个元素的值
问题描述
我有一个名为this.itemsArray
. 数组内的对象包含属性rate
。rate
是[(ngModel)]
在用户输入值时设置的。
每当用户输入时rate
,我想显示下面的按钮。如果用户没有输入rate
,那么我想隐藏按钮。
如果数组中只有 1 个项目(因此只有一个速率),则代码可以正常工作。当有多个项目(因此数组中有多个速率)时,问题就出现了。在这种情况下,问题在于仅当数组中的最后一项(速率)具有值时按钮才被隐藏。
每当数组中的任何比率为空白时,我都需要隐藏该按钮。我怎样才能做到这一点?
<div *ngFor = "let item of this.itemsArray; let i = index">
<button *ngIf = "this.itemsArray[i].rate" >Proceed</button>
</div>
解决方案
您已经在使用单个元素item
。为什么要用this.itemsArray[i].rate
??
<div *ngFor = "let item of this.itemsArray; let i = index">
<button *ngIf = "item && item.rate" >Proceed</button> // Replace this.itemsArray[i] with item
</div>
// the condition item && item.rate ==> it will check if the item is there and item.rate is there. If its not there, it wont display that element in the DOM
推荐阅读
- algorithm - 存储字典(单词)以优化搜索时间的良好数据结构是什么?
- c++ - 如何从 C++ 中的文本文件正文中获取特定的单词和行
- android - 当用户单击特定位置时,我想在地图上标记位置
- node.js - Express 会话属性未在架构中设置
- angular - 更改检测不适用于 NgFor 中使用的复杂对象
- python - 当我尝试用我的代码导入它时,为什么 sublime 找不到 pygame?
- neo4j - 在 Neo4j 中可视化连接组件
- cordova - 无法在浏览器 Ionic Cordova 中构建和添加平台
- azure - ST_DISTANCE 返回什么单位?
- python - 是否可以在 Python 中动态地为内置的 Python 对象添加属性?