Responding to @The Fabio's comment beneath his answer and offering a potential solution to the initial question.
What are the drawbacks of using functions to evaluate classes in [ngClass]
? Or more broadly, why is it discouraged to incorporate function calls in Angular template expressions?
The issue arises from Angular's change detection mechanism needing to invoke the function to check for changes => when iterating through extensive lists, the function will be called numerous times even if there is no relevant alteration. This means the function gets executed whenever you interact with buttons, input fields bound to it, and so forth. Refer to the Stackblitz Demo.
To tackle this problem effectively, examining the original list and considering alternative approaches is key. I recommend utilizing the View Model, which extends properties of the original Data Model.
// Proposed Question View Model
// extending the original one allows adding new properties while retaining the old ones
interface IQuestionVM extends IQuestionDTO {
hasHighlight: boolean
}
//somewhere in the code, ngOnInit is a suitable place for this
this.processedQuestions: Array<IQuestionVM> = this.lists[0]question.map(q => ({
...q, // spread the original object
hasHighlight: q.something === 0 // evaluate the condition and assign to extended property
}))
This approach simplifies and optimizes the HTML template:
<span
*ngFor="let list of processedQuestions; let i = index" id="word{{ i }}"
(click)="changestyle($event)"
[ngClass]="{ 'highlight': list.hasHighlight }"
>
{{ list }}
</span>
This method removes the necessity for a dedicated function to assess the class, eliminates the need to search for elements manually, and streamlines handling highlight updates. No extra variables, arrays, functions, or jQuery are required anymore.