Ali
Ali

Reputation: 113

In NgFor cycle with NgIf

I am doing angular and from backend I have data. Data looks like:

{
 name: 'Name',
 surename: 'Surename',
 position: 'Goalkeeper'
},
{
 name: 'Name',
 surename: 'Surename',
 position: 'Defender'
}

And in HTML I have:

<mat-option *ngFor="let player of players" [value]="player">
  <div *ngIf="player.position === 'Goalkeeper'">
             {{player.name}} {{player.surename}} ({{player.price}}M)
  </div>
</mat-option>

But in result, I get free space after players, who is not in condition ngIf ... In real, looks like:

Image of mat-option in web

I add lines to better see free space on image.

What should I repair to remove free space? Thanks

Upvotes: 3

Views: 432

Answers (2)

Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14077

Approach suggested by Jota is very solid.

Anorher way would be to create a property in component class that would already have goalkeepers.

get goalkeepers() {
    return this.players.filter(p => p.position === 'Goalkeeper');
}

Then you could iterate over them 👌

Upvotes: 1

Jota.Toledo
Jota.Toledo

Reputation: 28434

The mat-option is rendered independent of the player, only its content change.

Refactor as follows:

<ng-container *ngFor="let player of players">
  <mat-option *ngIf="player.position === 'Goalkeeper'" [value]="player">
    {{player.name}} {{player.surename}} ({{player.price}}M)
  </mat-option>
</ng-container>

The perfect solution would be to use ngFor and ngIf in the mat-option, but its not possible to apply 2 structural directives on the same element. Due to this, you need to "expand" the template into the above.

Upvotes: 2

Related Questions