I want to automatically ionchange in ion-checkbox trigger

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() {
document.getElementsByClassName(“td”)[0].click();
} ← error. This is not usable too…

3>

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, you can use it, but how do you initialize it as all selected, while maintaining the existing functionality as well?

I need help, please.

These two will likley be fighting for control over the value and hence also the way it is displayed and interacts with the user. That will cause quite some confusion.

Use either one of them. Use ngModel to bind two ways, or use a single binding using [] on the value and the ionChange to change it.

document.getElementsByClassName(“td”)[0].click(); - better not do this - besides not being the Angular way. Also if you want a method to be called, just call it. Right?

What I would do is create an object and bind the ngModel to the attributes -especially if you have a list of checkboxes. You seem to be using an array for that. I don’t believe that works nicely.

And looking at your code, the missing piece for me to complete understand what you are doing is the “data” property - data.ischecked

So something like

…component.ts

myCheckboxes=['chekboxa','checkboxb']; // etc

isChecked={}

in constructor:

myCheckboxes.forEach(checkbox=>(isChecked[checkbox]=false)) // or any other default value

…component.html

<ion-item *ngFor="let checkbox of mycheckboxes>
<ion-label slot="start">{{checkbox}}</ion-label>
<ion-checkbox  slot="end" [(ngModel)]="isChecked[checkbox]"></ion-checkbox>
</ion-item>

You can add an ionChange on the checkbox, as long as it does not touch isChecked. More for sideeffects.

1 Like

Thank you for your kindness.

1 Like