I have a div like this
<div *ngFor='let step of steps; let i =index'>
somewhere outside the ngFor I have this
<span>Step 1 of {{steps.length}}</span>
I need to keep track of the index outside the ngFor so this works
<span>Step {{i+1}} of {{steps.length}}</span>
the result being 1 of 4, 2 of 4.....
is this possible?
<header>
<h1>form</h1>
<div>
<span>Step {{i+1}} of {{steps.length}}</span> // here is where I need the step index
<button (click)="previous()"
[disabled]="!hasPrevStep || activeStep.showPrev">Back</button>
<button (click)="next()" [disabled]="!activeStep.isValid"
[hidden]="!hasNextStep || activeStep.showNext">Next</button>
</div>
</header>
<nav>
<ul>
// here is where im looping over
<li *ngFor="let step of steps; let i = index"
(click)="goToStep(step)">
<span class="u-flex1">
<span>
<a class="button>{{step.title}}</a>
</span>
</span>
</li>
</ul>
</nav>
Steps to get index of ngFor element in Angular Declare a variable inside *ngFor directive using let or as keyword. for instance say indexofelement or simply i. Assign the variable value to index. And display the index of ngFor element using angular expression.
Yep, index as i is the latest Angular syntax for accessing the local index variable inside NgFor. In earlier Angular version you would use let i = index; and prior to that #i = index.
We can use the ngFor directive to iterate over arrays of data right in the Angular’s component template. We can use other features like index, first, last and trackBy to get the index of the current element, the first and last elements and for tracking the addition or removal of the array elements for performane reasons.
In earlier Angular version you would use let i = index; and prior to that #i = index. You could also use { { i }} directly inside the NgFor to log out the value - perhaps you’re using NgFor with a list or other scenario, but I like to think in components when possible.
<div *ngFor='let step of steps; let i =index'>
<button (click)="active = i" [enabled]="active !== i">make active</button>
</div>
<span>Step {{active+1}} of {{steps.length}}</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With