外部访问索引* ngFor in angular

时间:2017-05-23 15:59:32

标签: angular

我有这样的div

<div *ngFor='let step of steps; let i =index'>

在ng之外的某个地方我有这个

<span>Step 1 of {{steps.length}}</span>

我需要跟踪ngFor之外的索引,这样才能正常工作

<span>Step {{i+1}} of {{steps.length}}</span>

结果是4个中的1个,2个中的4个.....

这可能吗?

<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 个答案:

答案 0 :(得分:4)

<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>

答案 1 :(得分:0)

您可以将ngFor循环包装并仅在第一页之前显示当前页面。 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>

看起来您对用例没有太多考虑,或者您没有在问题中公布所有细节。它没有任何线索,如果你只想显示一个步骤就循环所有步骤,但你可以看到ng-container是如何工作的。它正在重复内容,但没有定义* ngFor的标签