How do I dynamically change the value of [checked] property in ion-checkbox?


<ion-list lines='full'>
  <ng-container *ngFor="let item of data">
      <ion-label class="ion-text-wrap">
          {{ item.Title}}
      <ion-checkbox slot="end"
      (ionChange)="onDataCheckBoxChange(item.Id, $event)" 

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?


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, ...] = number) => ({ id: id, selected: this.selectedIds.includes(id)});

onDataCheckBoxChange(itemId: number, checked: boolean) {
  if ( checked ) {
  } else {
    this.selectedIds = this.selectedIds.filter((id: number) => id !== itemId);
  } => === itemId).selected = checked;

Answered By – Simon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published