[FIXED] I want to automatically ionchange in ion-checkbox trigger

Issue

I made a check box that I can select from the list using the method below.

component.html

  <td class="td"> //The area of the check box.
    <ion-checkbox
      [(ngModel)]="data.isChecked"
      (ionChange)="checkBox(data.isChecked)" //An event occurs when you actually click it.
    ></ion-checkbox>
  </td>

The relevant codes are as follows.

component.ts

checkBox(clicked) {
this.isUpdateBtnEnabled = clicked;
for (let i = 0; i < this.List.length; i++) { //[this.list] is a variable that contains the data in that list.
if (this.List[i].isChecked) {
this.isUpdateBtnEnabled = this.List[i].isChecked;
break;
}
}
}

It works normally, but in addition to this, when I first loaded the page, I want all the check boxes selected. Here’s what I’ve tried.

1>
component.html → checked=“true”

  <td class="td"> // The area of the check box.
    <ion-checkbox
      checked="true" // It will not work unless you erase the two lines below. This is not usable.
      [(ngModel)]="data.isChecked"
      (ionChange)="checkBox(data.isChecked)" 
    ></ion-checkbox>
  </td>

2>
component.ts → ngOnInit

ngOnInit() {
document.getElementsByClassName(“td”)[0].click();
} // error. This is not usable too…

3>
component.ts → ngOnInit

ngOnInit() {
let form = document.getElementById(‘td’);
if (form) {
(form as HTMLFormElement).click();
} // There is no error, but it is not selected. This is not usable too…
}

If it’s just for selection, can use [component.html → checked=“true”], but how do you initialize it as all selected, while maintaining the existing functionality as well?

Solution

I don’t know how your list is formated but as you want all checkbox to be checked at the start :

  • you can use *ngFor to display your data
  • you format your data with a isChecked value (true for the start)
  • you can still use and adapt your logic with your event listener

HTML file

<ion-item *ngFor="let entry of myList">
 <ion-label>{{entry.val}}</ion-label>
 <ion-checkbox slot="end" checked="entry.isChecked" (ionChange)="yourFunction(entry.isChecked)></ion-checkbox>
</ion-item>

TS file

myList = [{val: 'option 1', isChecked: true}, {val: 'option 2', isChecked: true}, {val: 'option 3', isChecked: true}];

Answered By – uKioops

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published