只有在 *ngIf 中的所有选项都不为真时才显示 else 块
Only display else block if ALL options in *ngIf fail to be true
我在 *ngIf
中有多个选项,由 ||
运算符分隔。我还有一个 else
运算符设置来显示是否为真。问题是,它在每个操作而不是整体上显示 else 块。
NgIf 块与 ngFor
<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>
我只希望在 ngFor 中根据 ngIf
中规定的参数没有显示任何内容时显示 else 块,而不是现在它在每个 运行 上显示 else共 ngFor
.
要只显示一个 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>
我在 *ngIf
中有多个选项,由 ||
运算符分隔。我还有一个 else
运算符设置来显示是否为真。问题是,它在每个操作而不是整体上显示 else 块。
NgIf 块与 ngFor
<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>
我只希望在 ngFor 中根据 ngIf
中规定的参数没有显示任何内容时显示 else 块,而不是现在它在每个 运行 上显示 else共 ngFor
.
要只显示一个 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>