Search code examples
angulartypescriptngforangular-ng-if

ngIf Display Another DOM Element in Angular 2


Not sure if this is possible, but I am building a dynamic HTML table of products. I am evaluating each product's "updatedDate" and determining if that date is less than the current date minus 7 days - todayMinusSeven days is a variable I am declaring in my TypeScript component file initializing it to the current date minus seven days:

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

I am trying to figure out how to display my div element of id "notice" from the *ngIf condition in the HTML table. Essentially, if any product's updatedDate is less than the current date minus seven days, then display the "notice" div. Here is my 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>

Whether or I need to do this in the HTML or the component TypeScript file I am not sure, I am getting the list of products from an HTTP service class and subscribing it to an array of Product objects, so I would prefer not to have to traverse the array for this condition since it is already being traversed in the HTML markup. Is this possible to do in HTML with Angular 2/4?

Thanks!


Solution

  • The way I would handle this is to create something in your OnInit (or after your data is resolved- maybe OnChanges) where you process your array and determine if there are any values less than the required date. You want to do this in a pre/post process to prevent Angular from calling this in a function each time it has to refresh the DOM via change detection. It's better to bind the *ngIf to a public/protected property on the component than to calculate each time.

    I have created a Stackblitz example of what I mean