In NgFor cycle with NgIf

旧城冷巷雨未停 提交于 2019-12-14 03:51:18

问题


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


回答1:


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 👌




回答2:


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.



来源:https://stackoverflow.com/questions/55008924/in-ngfor-cycle-with-ngif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!