Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access index outside *ngFor in angular

Tags:

angular

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>
like image 514
Mel Pacheco Avatar asked May 23 '17 15:05

Mel Pacheco


People also ask

How to get index of ngfor element in angular?

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.

What is index as I in ngfor?

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.

How to iterate over an array using ngfor in angular?

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.

How do I log the value in ngfor?

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.


1 Answers

<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>
like image 115
Günter Zöchbauer Avatar answered Oct 08 '22 02:10

Günter Zöchbauer