jeudi 2 avril 2020

Checkbox state based on function Angular

In my component, I have two arrays of items: allItems and selectedItems (using dummy names here, of course). The selection is handled by checkbox controls and their state depends on whether an item is found in selectedItems.

Since I need to evaluate checkbox state based on an expression, I need to call a function, like so:

<div *ngFor="let item of allItems; let i = index">
    <input type="checkbox"
                [checked]="itemChecked(item .Id)"
                (change)="toggleItem(i)">
    <label class="form-check-label" [for]="item.Id"></label>
</div>

And the function goes something like:

itemChecked(id: number) {
    return this.selectedItems.findIndex(x => x.Id == id) > -1;
}

The problem is the itemChecked executes nonstop. I've read before this can maybe be solved using directives, but if that is even the case, I can't find any concrete example.

Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire