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…
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()