In Angular I have a long list of words which I display in template as <li>
using *ngFor
loop.
Because the list is so long, I want to make sections by initial letter. The list is already sorted alphabetically.
Usually I would have a variable for current letter. Then iterate the list and if the first letter of the current word does not equal the variable, I would display the new letter once in bold. Then I would re-assign the new letter to the variable and continue.
I sure can test *ngIf
the current word's 1st letter equals the variable.
However in Angular I cannot re-assigning that variable in template.
What would be the best way to do this?
<div *ngFor="let word of list">
<div *ngIf="initial !== word[0]">
<!-- this does not work: {{ initial = word[0] }} -->
<b>{{ word[0] }}</b>
</div>
<li>{{ word }}</li>
</div>
Performing operations in templates is not recommended.
I'd suggest you to prepare desired data structure in the component code and then render it using simple nested
*ngFor
.In your case I'd probably use:
As an alternative you could have flat list with two types of elements (initial & word) - it depends on your usecase: