我试图创建一个带有离子2和角度2的小购物车。现在,这是我的代码:
前面:
<ion-card *ngFor="let person of people;let i = index" >
<ion-card-header>{{person.name.first}} {{person.name.last}} {{i}}</ion-card-header>
<ion-item>
<ion-icon name="add-circle" (click)="incrementQty(i)" item-right></ion-icon>
<ion-input type="number" min="1" [value]="qty" [(ngModel)]="qty"></ion-input>
<ion-icon name="remove-circle"(click)="decrementQty(i)" item-right></ion-icon>
</ion-item>
</ion-card>
.ts文件:
incrementQty(index:number){
console.log(this.people[index]);
this.qty += 1;
}
我的问题是我只想增加点击的元素,而不是全部!
我是棱角分明2的新手,并且不知道如何解决这个问题,谢谢你的帮助!
答案 0 :(得分:2)
我可以想到两种可能的解决方案:
选项-1 强>
让qty
成为person
对象的属性,并在incrementQty
方法中this.people[index].qty += 1
private quantities: number[];
constructor() {
this.people = this.people.map(person => {
person['qty'] = 0;
return person
});
}
incrementQty(index:number){
this.people[index].qty += 1;
}
HTML:
<ion-card *ngFor="let person of people;let i = index" >
<ion-card-header>{{person.name.first}} {{person.name.last}} {{i}}</ion-card-header>
<ion-item>
<ion-icon name="add-circle" (click)="incrementQty(i)" item-right></ion-icon>
<ion-input type="number" min="1" [value]="person.qty" [(ngModel)]="person.qty"></ion-input>
<ion-icon name="remove-circle"(click)="decrementQty(i)" item-right></ion-icon>
</ion-item>
</ion-card>
选项-2 强>
在(可能在qty
)组件代码中创建一个constructor
数组。数组的大小应与people
数组的大小相同。将初始值设置为0.在代码中,可以将索引中的数量增加到与人数组中人员索引相同的索引。
private quantities: number[];
constructor() {
this.quantities = new Array(this.people.length);
this.quantities= this.quantities.map((el: any) => 0);
}
incrementQty(index:number){
this.quantities[index] += 1;
}
HTML:
<ion-card *ngFor="let person of people;let i = index" >
<ion-card-header>{{person.name.first}} {{person.name.last}} {{i}}</ion-card-header>
<ion-item>
<ion-icon name="add-circle" (click)="incrementQty(i)" item-right></ion-icon>
<ion-input type="number" min="1" [value]="quantities[i]" [(ngModel)]="quantities[i]"></ion-input>
<ion-icon name="remove-circle"(click)="decrementQty(i)" item-right></ion-icon>
</ion-item>
</ion-card>
答案 1 :(得分:1)
每qty
您需要一个person
值,目前您只有一个用于整个组件。
qty:number[];
loadPeople(){
this.peopleService.load()
.then(data => {
this.people = data;
this.qty = new Array(this.people.length);
});
}
incrementQty(index:number){
console.log(this.people[index]);
this.qty[index] += 1;
}
<ion-card *ngFor="let person of people;let i = index" >
<ion-card-header>{{person.name.first}} {{person.name.last}} {{i}}</ion-card-header>
<ion-item>
<ion-icon name="add-circle" (click)="incrementQty(i)" item-right></ion-icon>
<ion-input type="number" min="1" [value]="qty[i]" [(ngModel)]="qty[i]"></ion-input>
<ion-icon name="remove-circle"(click)="decrementQty(i)" item-right></ion-icon>
</ion-item>
</ion-card>