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