我试图在网格中绘制一组满足条件的项目,但迭代不符合条件,并且仍然在视图中绘制空网格项。如何阻止 *ngFor(或任何负责人员)绘制
<div class="grid main" *ngIf="blogPosts$ | async as blogPosts">
<div class="tile" *ngFor="let blogPost of blogPosts.items">
<div *ngIf="blogPost.fields.category == this.catLink.getCat()">
<div (click)="catLink.setCat(blogPost.fields.category)"
[routerLink]="['/article', blogPost.sys.id]" >
<img width="375" height="250" [src]="blogPost.fields.featuredImage.fields.file.url" alt="">
<div class="title"><span>{{ blogPost.fields.title }}</span></div>
</div>
</div>
</div>
</div>
请记住,更好的解决方案是在代码中而不是在模板中过滤数据,这可能会有所帮助。
我猜空元素是带有一类瓷砖的div
。它总是被打印的,因为你迭代一个div
,它会在DOM中插入一个元素。您还可以打印带有嵌套 NgIf 的div
。
请尝试改用<ng-container>
,并仅在满足条件时才打印。
<div class="grid main" *ngIf="blogPosts$ | async as blogPosts">
<ng-container *ngFor="let blogPost of blogPosts.items">
<ng-container *ngIf="blogPost.fields.category == this.catLink.getCat()">
<div class="tile">
<div>
<div (click)="catLink.setCat(blogPost.fields.category)"
[routerLink]="['/article', blogPost.sys.id]" >
<img width="375" height="250" [src]="blogPost.fields.featuredImage.fields.file.url" alt="">
<div class="title"><span>{{ blogPost.fields.title }}</span></div>
</div>
</div>
</ng-container>
</ng-container>
</div>