【问题标题】:ngFor is only setting value of last elementngFor 只是设置最后一个元素的值
【发布时间】:2021-01-14 18:33:35
【问题描述】:

我有一个名为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>

【问题讨论】:

  • 不要使用let i = index,使用index as iangular.io/api/common/NgForOf
  • 另外,也不需要使用索引;你可以参考item
  • 您使用的是哪个 Angular 版本?
  • 我将let i = index 更改为index as i。我还将this.itemsArray[i].rate 更改为item.rate,但仍然遇到同样的问题。我正在使用Angular: 10.1.0
  • 预期的行为有点不清楚。假设您在数组中有两个项目,并且其中只有一个设置了速率。是否要显示该项目的按钮而不是其他项目的按钮?

标签: javascript arrays angular ngfor angular-ng-if


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您应该在 ts 文件中的某个位置处理项目(例如 this.hideButton = this.itemsArray.some(item =&gt; !item.rate)),然后在模板中处理 &lt;button *ngIf = "!hideButton" &gt;Proceed&lt;/button&gt;

    【讨论】:

    • 我会尽快尝试并回复您。谢谢!
    猜你喜欢
    • 2019-01-30
    • 2015-07-16
    • 2014-06-25
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2021-05-16
    • 2017-04-08
    • 1970-01-01
    相关资源
    最近更新 更多