我尝试创建按钮增量,减量
我只需要增加或减少一个输入,但它会增加或减少所有输入
在body.component.html
中
<div class="items-detail-detail" *ngFor="let detail of card.detail">
<div class="items-detail-information3">
<div class="btn-block" >
<button class="btn btn-default" (click)="onDecrement()">
<i class="material-icons">remove</i>
</button>
</div>
<div class="input-group" >
<input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
</div>
<div class="btn-block">
<button class="btn btn-default" (click)="onIncrement()">
<i class="material-icons">add</i>
</button>
</div>
</div>
在body.component.ts
中
export class BodyComponent implements OnInit {
private counter : number = 0;
onIncrement() {
this.counter++
}
onDecrement() {
this.counter--
}
ngOnInit() {
}}
代码将像这样运行
如果我在顶部按钮中按[+],它将[+]所有输入
抱歉我的英文
非常感谢你
答案 0 :(得分:0)
您必须维护所有cards
的计数器变量。
<div class="items-detail-detail" *ngFor="let detail of card.detail">
<div class="items-detail-information3">
<div class="btn-block" >
<button class="btn btn-default" (click)="onDecrement(detail)">
<i class="material-icons">remove</i>
</button>
</div>
<div class="input-group" >
<input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
</div>
<div class="btn-block">
<button class="btn btn-default" (click)="onIncrement(detail)">
<i class="material-icons">add</i>
</button>
</div>
</div>
export class BodyComponent implements OnInit {
private counter: number = 0;
onIncrement(item) {
item.counter = item.counter ? item.counter + 1 : 1;
}
onDecrement(item) {
item.counter = item.counter ? item.counter - 1 : 0;
}
ngOnInit() {}
}
答案 1 :(得分:0)
您遇到的问题是因为您的所有信用卡详细信息都有counter
。
<div class="input-group" >
<input type="number" value="{{counter}}" class="form-control" style="text-align:center;" >
</div>
如果您想更新单张卡的值,则需要设置不同的counter
值。
答案 2 :(得分:0)
@ A.Yo,您的详细信息必须是属性&#34; counter&#34;,因此,您增加此属性,而不是全局属性
<div class="items-detail-detail" *ngFor="let detail of card.detail">
...
<!--in button, you pass as argument "detail"-->
<button class="btn btn-default" (click)="onDecrement(detail)">
...
<!--the value is NOT counter, it's detail.counter -->
<input type="number" value="{{detail.counter}}" class="form-control" style="text-align:center;" >
...
<!--idem with onIncrement--->
<button class="btn btn-default" (click)="onIncrement(detail)">
...
</div>
//private counter : number = 0; <--NOT, I don't use a "global" variable
onIncrement(detail:any) {
detail.counter++ //<--increment "detail.counter"
}
onDecrement(detail:any) {
detail.counter-- //<--decrement "detail.counter"
}
您可以使用
简化代码<button class="btn btn-default" (click)="detail.counter++">
<input type="number" value="{{detail.counter}}">
<button class="btn btn-default" (click)="detail.counter--">