ngIf 显示 Angular 中的另一个 DOM 元素 2

ngIf Display Another DOM Element in Angular 2

不确定这是否可行,但我正在构建一个动态的 HTML table 产品。我正在评估每个产品的 "updatedDate" 并确定该日期是否小于当前日期减去 7 天 - todayMinusSeven 天是我在初始化它的 TypeScript 组件文件中声明的变量到当前日期减去 7 天:

this.todayMinusSeven = new Date();
this.todayMinusSeven.setDate(this.todayMinusSeven.getDate() - 7);

我想弄清楚如何根据 HTML table 中的 *ngIf 条件显示我的 div 元素 "notice"。本质上,如果任何产品的更新日期小于当前日期减去七天,则显示 "notice" div。这是我的 HTML:

<div id="notice" class="err-notice">
    <img src="../error.svg" />
    There are products that have not been updated in the past seven days...please notify the support department for further information
</div>
<table>
    <thead>
        <th></th>
        <th>ID</th>
        <th>Name</th>
        <th>Updated On</th>
    </thead>
    <tbody>
        <tr *ngFor="let product of products?.results">
            <td>
                <ng-container *ngIf="product.updatedOn < todayMinusSeven"; else nonotice;">
                    <img src="../error.svg" />
                </ng-container>
                <ng-template #nonotice>
                    <img *ngIf="selected" src="../product-open.svg" />
                    <img *ngIf="!selected" src="../product.svg" />
                </ng-template>
            </td>
            <td>{{product.id}}</td>
            <td>{{product.name}}</td>
            <td>{{product.updatedOn}}</td>
        </tr>
    </tbody>
</table>

我不确定是否需要在 HTML 或组件 TypeScript 文件中执行此操作,我正在从 HTTP 服务 class 获取产品列表并将其订阅到Product 对象的数组,所以我宁愿不必为此条件遍历数组,因为它已经在 HTML 标记中被遍历了。这可以在 HTML 中用 Angular 2/4 完成吗?

谢谢!

在支持页面的 Typscript 代码中添加一个名为 isOutDated() 的实用程序方法,该方法会遍历产品和 returns 一个布尔值。添加 *NgIf="isOutDated()" 到 div with id notice

我处理这个问题的方法是在您的 OnInit 中创建一些东西(或者在您的数据被解析之后 - 可能是 OnChanges),您在其中处理您的数组并确定是否有任何值小于所需的日期。您希望在 pre/post 进程中执行此操作,以防止 Angular 每次必须通过更改检测刷新 DOM 时在函数中调用它。最好将 *ngIf 绑定到组件上的 public/protected 属性 而不是每次都计算。

我已经创建了一个 Stackblitz example 我的意思