1 . I have several buttons on the same page, as you can see below:
2 . Once any of them clicked it shows the below button
The issue:
I have a page that contains several ADD buttons like in ( 1 ), if I click on the first button (then it shows the incrementing/decrementing button like in ( 2 ) which is totally normal). Then, if I click the second, third.... ADD button, (the incrementing/decrementing button (2) disappears from other buttons even if I already incremented/decremented values in that button).
The code:
HTML
<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 {
//THIS IS THE ADD BUTTON
addTo(element){
this.currentEl = element;
}
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 should I do to solve the issue?
I've assumed you are trying to implement a cart with items. Please see below for implementation.
//our root app component import {Component} from '@angular/core' @Component({ selector: 'my-app', providers: [], template: ` <b>Items:</b> <div *ngFor="#item of list"> <label>{{item.name}}</label> <div *ngIf="hasItem(item)"> <tr> <td> <input type="button" (click)="dec(item)" value="Down"/> <input type="text" [value]="item.total"/> <input type="button" (click)="inc(item)" value="Up"/> </td> </tr> </div> <button (click)="inc(item)" *ngIf="!hasItem(item)">ADD</button> </div> <hr/> <div> <b>My Cart:</b> <div *ngFor="#item of list"> <label>{{item.name}}</label>: <span>{{item.total}}</span> </div> </div> `, directives: [] }) export class App { list = [{name: "Banana", total: 0}, {name: "Apple", total: 0}, {name: "Kiwi", total: 0}, {name: "Milk", total: 0}]; //THIS IS THE ADD BUTTON inc(item) { item = this.list.filter(obj => obj.name === item.name); var nItem = parseInt(item[0].total); if(nItem < 5) { nItem +=1; item[0].total = nItem; } } dec(item) { item = this.list.filter(obj => obj.name === item.name); var nItem = parseInt(item[0].total); if(nItem > 0) { nItem -=1; item[0].total = nItem; } } hasItem(item) { console.log(this.list.filter(obj => obj.name === item.name)[0].total); return this.list.filter(obj => obj.name === item.name)[0].total > 0; } constructor() { } }
complete implementation is in the Plnkr code: https://plnkr.co/edit/2SZCQoyMi5aOZpjYB4sL?p=preview
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.