我有一个数组中的付款类型列表
paymentTypes: Array<object> = [
{
id: 0,
name: 'Type 1'
},
{
id: 1,
name: 'Type 2'
},
{
id: 2,
name: 'Type 3'
},
{
id: 3,
name: 'Type 4'
},
{
id: 4,
name: 'Type 5'
}
];
允许用户选择付款方式。从用户选择付款类型开始,它就会传递到临时数组,并在执行此操作后向用户显示确认按钮。
tempPaymentArray: Array<object> = [];
这使用户可以确认他们要使用此付款方式。
确定后,我要将确认的值传递给savedPaymentTypes数组
savedPaymentTypes: Array<object> = [];
此列表中的付款类型要求
<ul class="payment-type-list">
<li *ngFor="let type of paymentTypes">
<div class="saved-payment">
<span class="label" (click)="selectPaymentType($event, id)"> {{ type.name }} </span>
<div class="btn-remove" *ngIf="selected">
<button type="button" (click)="confirmSelection($event, id)"> Confirm </button>
</div>
</div>
</li>
<span *ngIf="savedPaymentTypesArray.length > 0">
<li *ngFor="let type of savedPaymentTypesArray">
<div class="saved-payment">
<span class="label"> {{ type.name }} </span>
<div class="btn-remove">
<button type="button" (click)="removePaymentType($event, id)"> Remove </button>
</div>
</div>
</li>
</span>
</ul>
selectPaymentType(event, id) {
console.log(event);
let i = 0;
for (i; i < this.paymentTypes.length; i++) {
const selectedType = this.paymentTypes.slice(id, 1);
this.selected = selectedType;
console.log('selectedType <<< :: >>> ', this.selected);
if (selectedType) {
this.tempPaymentArray.push(this.paymentTypes[i]);
}
break;
}
console.log('this.tempPaymentArray <<< :: >>> ', this.tempPaymentArray);
}
confirmSelection(event, id) {
for (let i = 0; i < this.tempPaymentArray.length; i++) {
const tempSelected = this.tempPaymentArray.slice(id, 1);
if (tempSelected) {
this.savedPaymentTypesArray.push(this.tempPaymentArray[i]);
}
}
console.log('this.savedPaymentTypesArray <<< :: >>> ', this.savedPaymentTypesArray);
}
removePaymentType(event, id) {
if (this.savedPaymentTypesArray.length > 0) {
this.savedPaymentTypesArray.splice(id, 1);
}
console.log('removing ' + `${this.savedPaymentTypesArray}` + ' from savedPaymentTypesArray <<< :: >>> ', this.savedPaymentTypesArray);
}
当前正在发生什么。当用户单击付款类型时,它会为列表中的每种付款类型显示确认按钮,这不会发生。用户只希望看到他们选择的特定付款类型的确认按钮。同样发生的是,当我单击任意选项时,来自paymentTypes数组的相同索引值将被传递到tempPaymentArray,然后在单击确认按钮时将其保存到savedPaymentTypesArray。
因此它可以保存
0: {id: 0, name: "Type 1"}
1: {id: 0, name: "Type 1"}
2: {id: 0, name: "Type 1"}
3: {id: 0, name: "Type 1"}
4: {id: 0, name: "Type 1"}
而不是像这样
0: {id: 0, name: "Type 1"}
1: {id: 3, name: "Type 4"}
2: {id: 1, name: "Type 2"}
3: {id: 2, name: "Type 3"}
4: {id: 4, name: "Type 5"}