首页 > 解决方案 > ngFor 只是设置最后一个元素的值

问题描述

我有一个名为this.itemsArray. 数组内的对象包含属性raterate[(ngModel)]在用户输入值时设置的。

每当用户输入时rate,我想显示下面的按钮。如果用户没有输入rate,那么我想隐藏按钮。

如果数组中只有 1 个项目(因此只有一个速率),则代码可以正常工作。当有多个项目(因此数组中有多个速率)时,问题就出现了。在这种情况下,问题在于仅当数组中的最后一项(速率)具有值时按钮才被隐藏。

每当数组中的任何比率为空白时,我都需要隐藏该按钮。我怎样才能做到这一点?

 <div *ngFor = "let item of this.itemsArray;  let i = index">
                                                                            
     <button  *ngIf = "this.itemsArray[i].rate" >Proceed</button>

</div>

标签: javascriptarraysangularngforangular-ng-if

解决方案


您已经在使用单个元素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


推荐阅读