<ion-list lines='full'>
<ng-container *ngFor="let item of data">
<ion-item>
<ion-label class="ion-text-wrap">
{{ item.Title}}
</ion-label>
<ion-checkbox slot="end"
(ionChange)="onDataCheckBoxChange(item.Id, $event)"
[checked]="item.selected"
></ion-checkbox>
</ion-item>
</ng-container>
</ion-list>现在在ngOnInit()上,我返回一个项目ids数组,例如1,23,4,5,6等
现在,如果item.Id在我返回的items ids数组中,我希望选择[checked]属性。
到目前为止,我已经尝试在checkbox上创建另一个循环,但它重复了所有的复选框。
我怎样才能做到这一点呢?
发布于 2021-09-29 09:15:27
您可以做的是将数字数组(例如1,2,3,4,5, ...)映射到对象数组(例如[{ id: 1, selected: true }, { id: 2, selected: false}, { id: 2, selected: true }, ...]),然后还更新onDataCheckBoxChange函数中的选定值。
ngOnInit() {
...
// this.selectedIds: number[] - contains the initially selected ids
// numbers: number[] - contains all the numbers e.g. [1,2,3, ...]
this.data = numbers.map((id: number) => ({ id: id, selected: this.selectedIds.includes(id)});
}
onDataCheckBoxChange(itemId: number, checked: boolean) {
if ( checked ) {
this.selectedIds.push(itemId);
} else {
this.selectedIds = this.selectedIds.filter((id: number) => id !== itemId);
}
this.data.find((item) => item.id === itemId).selected = checked;
}发布于 2021-09-29 08:36:58
我不太了解ion,但我的方法是编写一个函数,如果checkbox的id在数组中,该函数将返回true,如下所示:
isChecked(itemId) {
return (checkedIds.find((id) => id === itemId) !== undefined ? true : false);
}然后在复选框上调用它
编辑:假设你的ids是数字
Edit2:也许你可以使用SelectionModel。
发布于 2021-10-19 05:30:32
您只需创建数组并将值(如true或false )传递为ion-复选框只接受true或false。
demoArr: any = [
{ id: 1, selected: true },
{ id: 2, selected: false },
{ id: 3, selected: true },];在html端,像这样做,你会得到你的输出。
我创建了一个示例,你可以在这里查看:https://stackblitz.com/edit/ionic-qzpmhu?file=app/main.ts
https://stackoverflow.com/questions/69372724
复制相似问题