IGJ
IGJ

Reputation: 95

ngFor is only setting value of last element

I have an array of objects called this.itemsArray. The object inside the array contains the attribute rate. The rate is set using [(ngModel)] when the user enters a value.

Whenever the user enters the rate, I want to show the button below. If the user does NOT enter the rate, then I want to hide the button.

The code works fine if there is only 1 item (and hence one rate) in the array. The issue comes when there are more than one items (and hence more than one rate in the array). In this case, the problem is that the button is being hidden ONLY when the LAST item (rate) in the array has a value.

I need the button to be hidden whenever ANY of the rates in the array are blank. How can I achieve this?

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

</div>

Upvotes: 0

Views: 1446

Answers (2)

Srikar Phani Kumar M
Srikar Phani Kumar M

Reputation: 1384

You already are using a single element item. Why to use 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

Upvotes: 2

D Pro
D Pro

Reputation: 1786

you should process the items at some point in the ts file (smth like this.hideButton = this.itemsArray.some(item => !item.rate)) and then in the template <button *ngIf = "!hideButton" >Proceed</button>

Upvotes: 0

Related Questions