Search code examples
angularcheckboxangular-templateangular-changedetection

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">{{ item.Value }}</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.


Solution

  • You can create a custom pipe in order to check for changes.

    The custom pipe

    @Pipe({
      name: 'isItemChecked'
    })
    export class IsItemCheckedPipe implements PipeTransform {
    
      transform(selectedItems: any[], id: number) {
        return selectedItems.findIndex(x => x.Id === id) > -1;
        // Or
        // return selectedItems.some(x => x.Id === id);
      }
    
    }
    

    And in the template:

    <input type="checkbox"
                    [checked]="selectedItems | isItemChecked:item.Id"
                    (change)="toggleItem(i)">