Home > Blockchain >  How to express Angular condition more succinctly
How to express Angular condition more succinctly

Time:09-29

How can I write the following more succinctly?

<table class="table">
    <thead>
        <tr *ngFor='let entry of m_myArray; let i = index'>
            <td *ngIf="i == m_myArray.length - 1"><a href=”” (click)="$event.preventDefault();OnShowRecentRecord()">{{getDateFormat(entry.date)}}</a></td>
            <td *ngIf="i != m_myArray.length - 1"{{getDateFormat(entry.date)}}</td>
        </tr>
    </thead>
</table>

If i == m_myArray.length - 1 I want the table entry to be a link, otherwise just text. I have used a test on i against m_myArray.length twice and feel like I should be able to use ngElse (or similar) to avoid that.

CodePudding user response:

In the angular world, when you are using ngFor directive, you have access to many variables. The ones that you are looking for is:

  • last which is true for the last element (exactly) for your case
<table class="table">
    <thead>
        <tr *ngFor='let entry of m_myArray; let i = index; let isLast = last'>
            <td *ngIf="isLast"><a href=”” (click)="$event.preventDefault();OnShowRecentRecord()">{{getDateFormat(entry.date)}}</a></td>
            <td *ngIf="!isLast">{{getDateFormat(entry.date)}}</td>
        </tr>
    </thead>
</table>

CodePudding user response:

here is stackblitz code sample

<table class="table">
  <thead>
    <tr *ngFor="let entry of m_myArray; let i = index">
      <div *ngIf="i == m_myArray.length - 1; else notLastIndex">
        <td><a href="””">link</a></td>
      </div>

      <ng-template #notLastIndex>
        <td>{{ entry }}</td>
      </ng-template>
    </tr>
  </thead>
</table>
  • Related