6
votes

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>
2
What value should i have outside of *ngFor? I can't make sense of your requirement from the code in the question. - Günter Zöchbauer
Why do not you have something like selectedIndex? - yurzui
I have 4 steps, i want to show which step is active 1 of 4, 2 of 4..... - Mel Pacheco

2 Answers

8
votes
<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>
0
votes

you can wrap you ngFor loop in and display the current page only before the first one. https://angular.io/docs/ts/latest/guide/structural-directives.html#!#ng-container

<ng-container *ngFor='let step of steps; let i =index'>
  <span *ngIf='step.isActive'>Step {{i+1}} of {{steps.length}}</span>
  <div>Step content</div>
</ng-container>

It looks like you do not think a lot about the use-case or you did not publish all details in the question. It has no clue, to loop all steps if you want to display only one, but you can see how ng-container is working. It is repeating the content, but without the tag where *ngFor is defined