* ngIf和* ngFor在同一元素

时间:2018-01-24 14:48:53

标签: angular ionic-framework

我在同一元素上使用*ngFor*ngIf时遇到问题。

  <div
    *ngFor="let recipeStep of RecipeSteps; let i = index"
    *ngIf="position === i">
    {{ recipeStep }}
  </div>

  <button ion-button small (click)="previous()">Previous</button>
  <button ion-button small (click)="next()">Next</button>
  

我知道简单的解决方案是在新元素上移动*ngIf。   例如:

<ng-container *ngIf="position === i">
 <div *ngFor="let recipeStep of RecipeSteps; let i = index">
  {{ recipeStep }}
 </div>
<ng-container>

但是当我使用此解决方案时,我无法使用i变量。此解决方案隐藏了<ng-container>

上的所有元素

所以,这个按钮现在没用了

<button ion-button small (click)="previous()">Previous</button>
<button ion-button small (click)="next()">Next</button>

这个打字稿填写

position: number;
ionViewDidLoad() {
  this.position = 1; 
}

next() {
  this.position = this.position + 1;
}
previous() {
  this.position = this.position - 1;
}

我的问题是在同一元素上使用*ngFor*ngIf有不同的方法。

如果没有办法有不同的方式让这个按钮有用

2 个答案:

答案 0 :(得分:3)

你只需要将ngIf和ngFor放在一起:

 <div *ngFor="let recipeStep of RecipeSteps; let i = index">
  <ng-container *ngIf="position === i">{{ recipeStep }}</ng-container>
 </div>

答案 1 :(得分:0)

正如你在这个答案中看到的那样here Angular不支持在一个元素上使用多个结构指令。

您需要在*ngIf

中使用*ngFor
<div *ngFor="let recipeStep of RecipeSteps; let i = index">
  <div *ngIf="position === i">
   {{ recipeStep }}
  </div>
</div>
相关问题