如何添加依赖于* ngFor内部数据的单个元素?

时间:2019-04-17 05:24:05

标签: angular angular-template

我有一个应用程序,在其中循环遍历一系列alertMessages。对于每个alertMessage,我正在检查所有参数是否有效(alertmessage未标记为已删除,已读取等),并且它是否已创建。如果所有这些参数均无效,那么我不想显示警报消息。

但是我也想显示一个包含单词“ Today”的h2元素。但是,此h2仅应显示一次,并且仅在呈现警报消息时显示。

alerts-page.component.html

<ng-container *ngFor="let alertMessage of alertMessages$ | async">
  <ng-container *ngFor="let recipient of alertMessage.recipients">
    <ng-container *ngIf="parametersAreValid(recipient) && wasCreatedToday(alertMessage)">
      <alert [alertRecipient]="recipient [alertMessage]="alertMessage"> 
      </alert>
    </ng-container>
  </ng-container>
</ng-container>

alerts-page.component.ts

    parametersAreValid(alertRecipient: AlertRecipient): boolean {
        const isForCurrentUser = alertRecipient.recipientId === this.currentUser.id;
        const isNotMarkedAsDeleted = !alertRecipient.isDeleted;
        const isNotMarkedAsRead = !alertRecipient.isRead;
        const isShownWhenShowDeletedIsSetToTrue = (alertRecipient.isDeleted && this.showDeleted);
        const isShownWhenShowReadIsSetToTrue = (alertRecipient.isRead && this.showRead);
        return (isForCurrentUser) && (isShownWhenShowDeletedIsSetToTrue || isNotMarkedAsDeleted) &&
            (isNotMarkedAsRead || isShownWhenShowReadIsSetToTrue);
    }


    wasCreatedToday(alertMessage: AlertMessage): boolean {
        const today = moment();
        const alertSentAt = moment(alertMessage.sentAt);

        return moment(alertSentAt).isSame(today, 'day');

    }

1 个答案:

答案 0 :(得分:0)

您可以使用ngrx-utils库的ngLet指令。https://github.com/ngrx-utils/ngrx-utils 使用此伪指令,您可以将allertmessages存储在模板的局部变量中。 然后,您可以检查alertMessages.lenght> 0并使用* ngIf指令显示h2。

但是,我同意卡米尔(Kamil)的观点,您不应在模板中加入过多的逻辑