Issue
<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>
now on ngOnInit()
I am returning a an array of item ids i.e. 1,23,4,5,6 etc
Now I want the [checked]
property to be selected if item.Id
is in the array of items ids
I have returned.
So, far I have tried creating another loop on checkbox but it repeats all checkboxes.
How can I can achieve this?
Solution
what you can do is to map your array of numbers (e.g. 1,2,3,4,5, ...
) to an array of objects (e.g. [{ id: 1, selected: true }, { id: 2, selected: false}, { id: 2, selected: true }, ...]
) and then also update the selected value in the onDataCheckBoxChange
function.
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;
}
Answered By - Simon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.