gpt4 book ai didi

javascript - 我的 Angular2 代码有问题

转载 作者:行者123 更新时间:2023-11-30 16:05:11 25 4
gpt4 key购买 nike

1。我在同一个页面上有几个按钮,如下所示:

Add button Add button Add button

2。一旦他们中的任何一个点击它就会显示下面的按钮

added

问题:

我有一个包含多个ADD 按钮的页面,如 (1),如果我单击第一个按钮(然后它会显示递增/递减按钮,如(2) 这是完全正常的)。然后,如果我单击第二个、第三个... ADD 按钮,(递增/递减按钮 (2) 从其他按钮中消失,即使我已经递增/递减该按钮中的值)。

代码:

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;
}
}
}

我应该怎么做才能解决这个问题?

最佳答案

我假设您正在尝试实现一个带有元素的购物车。请参阅下面的实现。

//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() {

}
}

完整的实现在 Plnkr 代码中:https://plnkr.co/edit/2SZCQoyMi5aOZpjYB4sL?p=preview

关于javascript - 我的 Angular2 代码有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37143547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com