如果* ng中的所有选项都为true,则仅显示else块

时间:2019-04-22 03:43:34

标签: angular angular-ng-if

我在*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

1 个答案:

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