Save checkbox values in ngFor


I hava a dynamic list and each list item got a checkbox. On top of that I have a search bar. When I check some items and then write something to the searchbar and the items do not fit to the search string then they dissappear as intended. But if I remove the search string, the items appear again but the checkboxes of these items are not checked anymore. So I guess I have to store the values of the checkboxes. My idea was to do it with ngModel, but how does it work inside of a ngFor loop?

I hope someone can help me with it

I had a similar case recently, ion-checkbox’s values are booleans, so what I did was to use an filters obejct to keep the state of each filter, e.g.

filters.field1 = true
filters.field2 = false

checkboxFields: string[];
filters: any;
constructor() {
   // initialize all checkbox fields (models)
   this.checkboxFields.forEach((field) => this.filters[field] = false )
Then use ngModel to bind each filter field to each checkbox
<ion-item *ngFor="let field of filters">
  <ion-checkbox [(ngModel)]="filters[field]"></ion-checkbox>

I suppose you could use (click) too which might be a bit more manual.

1 Like

Isn’t a better option just to use “let field of checkboxFields; let i = index;” then use checkboxFields[i] in your ngModel?

1 Like