签入 Angular/Ionic 应用程序后,复选框字段立即取消选中
Checkbox field immediately gets unchecked after checking in Angular/Ionic app
我在我的应用程序中循环访问了一系列数据。每个项目都包含字段 checked
,表示是否应选中该项目的复选框。默认情况下,在我的 list.html
文件中设置为 checked: false
。
<ion-item lines="full" *ngFor="let item of items">
<ion-label [class.strike]="item.checked" class="ion-padding ion-text-wrap">
{{ item.title }}
</ion-label>
<ion-checkbox slot="start" [(ngModel)]="item.checked" mode="ios" (ionChange)="itemChecked(item)"></ion-checkbox>
</ion-item>
在使用 ionChange
更改选中的复选框时,我调用我的 itemChecked
方法将我的 item
传递给它。
async itemChecked(item: Item) {
console.log(item); //I can see checked has been updated.
await this.firestore.updateItemKey(item, 'checked');
}
然后,在我的 firestore
服务文件中,我像这样更新文档:
updateItemKey(item: Item, key: string) {
const itemDocRef = doc(this.firestore, `items/${item.id}`);
return updateDoc(itemDocRef, { key: item[key] });
}
但是,回到我的 list.html
文件,该项目没有被检查并且我的 firebase 数据库中没有正确更新任何内容?该项目快速显示为已选中,然后立即恢复为未选中。
关于导致此问题的我可能忽略或做错的事情有什么想法吗?
而不是 [(ngModel)]="item.checked"
我认为你应该直接使用 [checked]="item.checked"
,在 itemChecked()
中做 item.checked = !item.checked
因为你想更新 [checked] 绑定具有新的价值。当然,你也应该处理 ionChange 的 checked==false 结果。
我在我的应用程序中循环访问了一系列数据。每个项目都包含字段 checked
,表示是否应选中该项目的复选框。默认情况下,在我的 list.html
文件中设置为 checked: false
。
<ion-item lines="full" *ngFor="let item of items">
<ion-label [class.strike]="item.checked" class="ion-padding ion-text-wrap">
{{ item.title }}
</ion-label>
<ion-checkbox slot="start" [(ngModel)]="item.checked" mode="ios" (ionChange)="itemChecked(item)"></ion-checkbox>
</ion-item>
在使用 ionChange
更改选中的复选框时,我调用我的 itemChecked
方法将我的 item
传递给它。
async itemChecked(item: Item) {
console.log(item); //I can see checked has been updated.
await this.firestore.updateItemKey(item, 'checked');
}
然后,在我的 firestore
服务文件中,我像这样更新文档:
updateItemKey(item: Item, key: string) {
const itemDocRef = doc(this.firestore, `items/${item.id}`);
return updateDoc(itemDocRef, { key: item[key] });
}
但是,回到我的 list.html
文件,该项目没有被检查并且我的 firebase 数据库中没有正确更新任何内容?该项目快速显示为已选中,然后立即恢复为未选中。
关于导致此问题的我可能忽略或做错的事情有什么想法吗?
而不是 [(ngModel)]="item.checked"
我认为你应该直接使用 [checked]="item.checked"
,在 itemChecked()
中做 item.checked = !item.checked
因为你想更新 [checked] 绑定具有新的价值。当然,你也应该处理 ionChange 的 checked==false 结果。