angular 4 -using else conditions with ng-template in p-datatable. currently have 2 ngif inside the template, want to avoid using two ngif

Viewed 673

In a component I have a source code similar to this:

<ng-template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="body">
  <span *ngIf='row.job_id'>
    {{row.job_id}}
  </span>
  <span *ngIf='!row.job_id'>
    Job ID Not available
  </span>
</ng-template>

I want to use else condition with it inside a single ng-template. how can I achieve it?

2 Answers

If you only need to change the text inside the span you can simple use :

{{ row.job_id ? row.job_id : 'Job ID Not available' }} 

like this you avoid *ngIf

If you really want to use if/else this seem to work :

<ng-template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="body">
    <span *ngIf='row.job_id; else notAvailable'>
       {{row.job_id}}
    </span>
    <ng-template #notAvailable>
      <span>
        Job ID Not available
      </span>
    <ng-template>
</ng-template>

Wrap the else path in an ng-template tag, give it a template variable and then use this: *ngIf='row.job_id; else elsePath;'

Something along the lines of this:

<ng-template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="body">
  <span *ngIf='row.job_id; else elsePath;'>
    {{row.job_id}}
  </span>
  <ng-template #elsePath>
    Job ID Not available
  </ng-template>
</ng-template>

Alternatively

Just use a ternary operator:

<ng-template let-col let-row="rowData" let-rowIndex="rowIndex" pTemplate="body">
  <span>
    {{ row.job_id ? row.job_id : 'Job ID Not available' }} 
  </span>
</ng-template>
Related