I have a list of strings of which I want to display a subset as a numbered list. I managed to use *ngFor and *ngIf to display the items I want, but I am struggling with the numbering.
This is the list:
let fieldnames: string[] = ["Name", "Age", "Email", "Address", "Phone"];
I have an object mapping the fieldnames to booleans:
let valid: { [key: string]: boolean } = {
"Name": true,
"Age": false,
"Email": true,
"Address": true,
"Phone": false,
};
This is my HTML template:
<ng-container *ngFor="let fieldname of fieldnames; let i = index">
<div *ngIf="valid[fieldname] === false">
{{ i + 1 }}. {{ fieldname }}
</div>
</ng-container>
Current Output
2. Age
5. Phone
The index increments based on the for loop, independently of the condition, so the numbering of each item corresponds to its position in the list.
Desired Output
1. Age
2. Phone
I only want the items numbered which are actually displayed. Is there a way to increment a variable conditionally based on the evaluation of my *ngIf statement?
I considered writing a separate function that returns only the sublist of fieldNames for which the condition is true. I could then loop over the sublist and use the normal index. This doesn't seem very elegant though, is there a better way?