Reputation: 1204
Currently, I have an "ADD" button, once clicked, it shows a new div which gives the ability to the end-user to increase/decrease the quantity of the item that was added to cart (think of Amazon cart)
The issue: When I click that "ADD" button, I can increase the quantity of a particular item; however, once I increase the quantity of an item, I go to another item, and once I click "ADD", the previous item that I already increased its quantity it disappears!!
The code:
HTML: running a for loop of a list of 4 elements
<div *ngFor="#item of list">
<div *ngIf="currentEl === list">
<tr>
<td>
<input type="button" (click)="dec(elem)" value="Down"/>
<input type="text" #elem value="0"/>
<input type="button" (click)="inc(elem)" value="Up"/>
</td>
</tr>
</div>
</div>
<div (click)="addTo(list)" *ngIf="currentEl !== list">ADD</div>
JS:
let list = ["Banana", "Apple", "Kiwi", "Milk"];
export class App {
addTo(element){
this.currentDish = mem;
}
inc(elem)
{
var nItem = parseInt(elem.value);
if(nItem < 5)
{
nItem +=1;
elem.value = nItem;
}
}
dec(elem)
{
var nItem = parseInt(elem.value);
if(nItem > 0)
{
nItem -=1;
elem.value = nItem;
}
}
}
What I think: I think that I have a logical issue on my code, that, I unfortunately not able to figure it out.
I hope you can help, and please if you do just give me a brief explanation to know what's going on and to learn.
Upvotes: 1
Views: 124
Reputation: 2626
Every one of your inputs has the same ID:
<input type="text" #elem value="0"/>
The #elem
should be a unique value, which it is not when you have more than one item in your list.
Instead, run your methods on the item
and bind your input to a variable:
<td>
<input type="button" (click)="dec(item)" value="Down"/>
<input id="elem_{{item.id}}" [(ngModel)]="item.value" type="text"/>
<input type="button" (click)="inc(item)" value="Up"/>
</td>
And
inc(item) {
if(item.value < 5) {
item.value += 1;
}
}
This is assuming your item
list is made up of objects with at least two fields: id
and value
, for example (you don't actually need to use this code, its just for reference):
export interface Item {
id: number;
value: number;
name: string;
// Etc...
}
So your list declaration would be:
let list = [
{
id: 0,
value: 0,
name: 'Banana'
},
{
id: 1,
value: 0,
name: 'Apple'
},
// etc...
];
Now, whenever you click to increment the item's quantity, your inc()
function just needs to increment the value
parameter of the item
and Angular will connect the dots, changing the value of the input box (as well as any other instance where you display the value).
Neat! And one of the main features of Angular.
Upvotes: 1