Checkboxes do not "exist" until ticked!


I’m iterating over an array with for… of. The array contains the true/falses from a checkbox array.

I’m finding that the array is empty until the checkbox is ticked. They are initialised like this:

<ion-checkbox color="primary" checked="false" *ngIf="listitem.flavour === 'item'" [(ngModel)]="item_ticks[i]" (ionChange)="updateTicks()"></ion-checkbox>

As you can see, checked is already set to “false” so why is the ngModel item_ticks empty (null) until the checkboxes are checked?


Because ion-type-items update differently from Angular items. In general, though, even if you are working with pure Angular components, it’s bad practice to do variable manipulation in the template. Angular might evaluate and re-evaluate the expression thousands of time as part of its change detection. It makes your page slow. Use the constructor in the ts file to initialize your variables to some dummy values, and then re-initialize them to the correct values once those values are available, using Promise, Observable subscription, or whatever you need.


Why can it be bad to do variable manipulation the way I’m doing it?

I should add that item_ticks is already defined in the .ts like this:

item_ticks = [];


If you set checked to true for each element in the array in your ts controller, each operation is performed once. If you assign any value through the template, how many times is it executed? How many times per second is the expression evaluated as “Oh I don’t need to execute that again.” Maybe this does not matter in your specific situation, but in general, if you rely on the template, you have less control over page performance.


If that is the case why is there even a checked=‘false’ option in the template?

The checklist is constructed using ngIf and so is a variable length depending on the data passed to it. How can I initialise it? If they were set lengths I’d use the controller to switch them on and off on initialising the page. But they aren’t so…

  1. The examples in the Ionic documentation all show fixed-length choices. That’s less likely to cause a problem than a dynamic form where you could conceivably have 100 or more elements in your array.

  2. Ionic was originally built for small apps with a few pages. You can’t expect Ionic components to scale. This might change over the next couple years, but right now, it’s an issue.

  3. The short answer to your second question is one I already gave above: Promises, Observables, etc. For the longer, real answer, you need to learn the basics of reactive programming.


I heartily agree with everything @AaronSterling is saying here. That being said, what you are seeing is that an ngModel binding trumps the checked attribute. checked only takes effect if the checkbox does not have a model binding.


I’m now using a for loop to intialise the false state in the model with ionViewDidLoad()