0

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.

1 Answer 1

1

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)">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.