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

Time:09-29

<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?

CodePudding user response:

I don't know much about ion, but my approach would be writing a function, that returns true, if the id of the checkbox is in the array, like such:

isChecked(itemId) {
    return (checkedIds.find((id) => id === itemId) !== undefined ? true : false);
}

and then calling it on the checkbox

Edit: this is assuming your ids are numbers

Edit2: maybe you can use SelectionModel.

CodePudding user response:

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;
}

  • Related