'ngIf value does not update

When I use [ngIf] in a table to hide or show a row that says 'No records' the results renders properly initially - but if the ngIf equations changes it is not updated in the DOM

I am using a ptag below the table with the same ngIf equation and this element responds appropriately

What is going wrong with my table [ngif]?

<table mat-table [dataSource]="dataSource">

<ng-container matColumnDef="noRecord">
<td mat-footer *matFooterCellDef> No records</td>
</ng-container>

<ng-template [ngIf]="dataSource.data.length == 0">
<tr mat-footer-row *matFooterRowDef=['noRecord']></tr>
</ng-template>

</table>

<p *ngIf="dataSource.data.length == 0"> Empty</p>


Solution 1:[1]

As @DFSFOT mentioned, I would rather, you use *ngIf on the ng-container tag rather than use ng-template tag!

Any particular reason you are using ng-template tag??

These might be other ways to solve the issue.

1) Use ng-if and ng-container like this: 

<ng-container *ngIf="dataSource.data.length == 0">
    <tr mat-footer-row *matFooterRowDef=['noRecord']></tr>
</ng-container>

2) You can directly use *ngIf on the <tr> tag itself
<tr 
  *ngIf="dataSource.data.length == 0"
  mat-footer-row 
  *matFooterRowDef=['noRecord']
></tr>

3) You can use CSS on condition basis like this: 

// Define the class in your css/scss file
.d-none { 
  display: none 
}

// In your HTML you can use that class like this: 
<tr 
  [class.d-none]="dataSource.data.length == 0"
  mat-footer-row 
  *matFooterRowDef=['noRecord']
></tr>


4) Last but not least: if you want to use template-reference, you can do this: 

<table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="noRecord">
        <td mat-footer *matFooterCellDef> No records</td>
    </ng-container>

    <ng-container 
       *ngIf="dataSource.data.length == 0" 
       *ngTemplateOutlet="emptyRecordTemplate"
    >
    </ng-container>
</table>

<ng-template #emptyRecordTemplate>
  <tr mat-footer-row *matFooterRowDef=['noRecord']></tr>
</ng-template>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Srikar Phani Kumar Marti