I am working on a component that contains a list of items:
list: Array<MyType>;
Users have the ability to select and deselect elements by clicking on them:
toggleItem(item: MyType) {
if (this.selection.has(item)) {
this.selection.delete(item);
return;
}
this.selection.add(item);
}
The selected items are kept track of using a Set
:
selected: Set<MyType> = new Set();
Now, I want to toggle a CSS class and change the title
attribute based on whether an element is selected or not:
<button class="toggle"
type="button"
[ngClass]="{'selected': selection.has(item)}"
[title]="selection.has(item) ? 'Select' : 'Deselect'"
(click)="toggleItem(item)">
{{ item.title }}
</button>
I recently came across advice suggesting it's not optimal to evaluate function calls in Angular templates as they may be invoked frequently for change detection. For example:
[ngClass]="{'selected': selection.has(item)}"
Instead, it might be better to check a variable or property of the object directly, like this:
[ngClass]="{'selected': item.selected}"
Is this true? And will my current implementation affect performance? Should I consider adding a property to each item indicating its presence in the Set
?