Search code examples
angularangular-ng-if

Angular 5: *ngIf="isValid;else other_content" VS *ngIf="isValid" . *ngIf="!isValid"


This question is about understanding why one technique is better than the other. In angular 4/5, inside a template you can achieve the same thing by doing:

1) *ngIf-else syntax

<div *ngIf="isValid;else other_content">
    content here ...
</div>

<ng-template #other_content>other content here...</ng-template>

2) *ngIf="isValid" *ngIf="!isValid"

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>

The two syntax are perfectly valid, with the syntax 1, you can go a bit further like describe here, but is there any performance / best practice recommendations of using one versus the other ?


Solution

  • Two ngIf directives are compiled twice and result in two bindings instead of one.

    This becomes even more messy if the expression contains pipes:

    <div *ngIf="isValidAsync | async">...</div>
    <div *ngIf="!(isValidAsync | async)">...</div>
    

    will result in two subscriptions.

    ngIf else template is supported exactly to address this case and should be used as a rule of thumb.