在 NgFor 循环中与 NgIf

In NgFor cycle with NgIf

我正在做 angular 并且从后端我有数据。数据如下:

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

在 HTML 我有:

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

但结果是,我得到了免费 space 玩家之后,谁不在条件 ngIf ... 实际上,看起来像:

Image of mat-option in web

我添加线条以更好地查看图像上的免费 space。

我应该修复什么才能删除免费 space?谢谢

mat-option 独立于播放器呈现,只有其内容发生变化。

重构如下:

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

完美的解决方案是在 mat-option 中使用 ngForngIf,但不可能在同一元素上应用 2 个结构指令。由于这个原因,你需要"expand"把模板改成上面的

Jota 建议的方法非常可靠。

另一种方法是在已经有守门员的组件 class 中创建一个 属性。

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

然后你可以遍历它们