我在*ngIf
运算符分隔的||
中有多个选项。我还有一个else
运算符设置,以显示是否为真。问题是,它在每个操作上而不是整体上显示else块。
使用ngFor阻止NgIf
<ng-container *ngFor="let expense of expenses">
<div *ngIf="sortBy && sortByColor && sortCategory.color == expense.category.color || sortBy && sortByTitle && sortCategory.title == expense.category.title || !sortBy; else elseBlock>
....
</div>
<ng-template #elseBlock>
<p>This is the else block that should show up only when nothing is displayed above.</p>
</ng-template>
</ng-container>
我只希望在ngIf
中设定的参数的基础上,如果ngFor中什么都没有显示,则不显示else块,而是现在它在每次ngFor
上显示else
答案 0 :(得分:3)
要只显示一个elseBlock
,应将其置于ngFor
外部,处于ngIf
循环之外。如果将条件放在定义为箭头函数的组件的方法中:
isSortedExpense = (expense) => {
return !this.sortBy ||
this.sortByColor && this.sortCategory.color == expense.category.color ||
this.sortByTitle && this.sortCategory.title == expense.category.title;
}
您可以在外部ngIf
和内部ngIf
中调用它。可以使用Array.some()测试至少一个显示项目的存在:
<ng-container *ngIf="expenses?.some(isSortedExpense); else elseBlock">
<ng-container *ngFor="let expense of expenses">
<div *ngIf="isSortedExpense(expense)">
....
</div>
</ng-container>
</ng-container>
<ng-template #elseBlock>
<p>This is the else block that should show up only when nothing is displayed above.</p>
</ng-template>