1

I have a problem when I use *ngFor and *ngIf on the same element.

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

I know the easy solution is to move the *ngIf on a new element. For Example:

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

but when I use this solution I can't use i variable. and this solution hide all element on <ng-container>

So, this buttons is not useful now

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

this typescript fill

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

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

My question is Are there different way use *ngFor and *ngIf on the same element.

If there are no way are there different way to be this buttons useful

Amjed Omar
  • 853
  • 2
  • 14
  • 30

2 Answers2

4

You just need to put the ngIf and the ngFor the other way around:

 <div *ngFor="let recipeStep of RecipeSteps; let i = index">
  <ng-container *ngIf="position === i">{{ recipeStep }}</ng-container>
 </div>
Plog
  • 9,164
  • 5
  • 41
  • 66
  • 1
    This would produce an empty div for the "hidden" element. If the div has some styling (e.g. padding + border + margin), you will see it. You could keep the `ng-container` outside and swap only the directives, in order to remove the div completely. – ConnorsFan Jan 24 '18 at 15:13
2

As you can see in this answer here Angular does not support more than one structural directive on one element.

You need to use your *ngIf inside the *ngFor:

<div *ngFor="let recipeStep of RecipeSteps; let i = index">
  <div *ngIf="position === i">
   {{ recipeStep }}
  </div>
</div>
ChesterLaborde
  • 458
  • 5
  • 14