我有一个复选框列表设置,将所选项目添加到数组中,该数组将其发送给服务。我有一个按钮,它运行一个函数,在单击时清空数组,但复选框仍然被选中。
这里我选择项目,红色的X出现了,点击它将清除数组。
这是在我点击X之后,数组被清除,但是项目仍然被选中
page.ts
if (this.checkedItems.includes(item)) {
this.checkedItems = this.checkedItems.filter((value) => value != item);
} else {
this.checkedItems.push(item)
}
console.log(this.checkedItems);
}
createRoutine() {
this.workoutService.selectedWorkouts = this.checkedItems;
console.log(this.checkedItems);
}
uncheckAll(){
this.checkedItems = [];
}
page.html
<div>
<ion-searchbar placeholder="Search..." [(ngModel)]="filterTerm" animated="true"></ion-searchbar>
<ion-list class="accordion-list">
<ion-card size="full" >
<ion-card-header>
<ion-item class="workout-title">
<ion-card-title> Workouts</ion-card-title>
<a slot="end"><ion-icon name="close-outline" size="large" color="bic" *ngIf="checkedItems.length > 0" (click)="uncheckAll()"></ion-icon></a>
</ion-item>
</ion-card-header>
<ion-card-content>
<ion-list *ngFor="let workout of bic | filter:filterTerm | orderBy:'asc':'muscle'; let i = index;" class="workout-list" >
<ion-item>
<ion-label>{{workout.name}}</ion-label>
<ion-note>{{workout.muscle}}</ion-note>
<ion-checkbox slot="end" color="bic" (ionChange)="onChange(workout)"></ion-checkbox>
</ion-item>
</ion-list>
</ion-card-content>
</ion-card>
</ion-list>
</div>
所以我正在寻找一个解决方案,如何让uncheckAll()
事件在清除数组后取消复选框。
您需要为复选框设置一个[(ngModel)]
,这将保持复选框的选中状态。这应该与workout
节点有界。
例如,我们可以把它标记为[(ngModel)]="workout.isSelected"
。
InsideuncheckAll
循环遍历bic
数组,并将每个节点的isSelected
设置为false
伪代码
模板
<ion-list *ngFor="let workout of bic | filter:filterTerm | orderBy:'asc':'muscle'; let i = index;" class="workout-list">
<ion-item>
<ion-label>{{workout.name}}</ion-label>
<ion-note>{{workout.muscle}}</ion-note>
<ion-checkbox
slot="end"
color="bic"
[(ngModel)]="workout.isSelected"
(ionChange)="onChange(workout)"></ion-checkbox>
</ion-item>
</ion-list>
Component.ts
uncheckAll(){
this.checkedItems = [];
this.bic.forEach(node => node.isSelected = false);
}