3

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 ?

Tonio
  • 4,082
  • 4
  • 35
  • 60
  • 5
    Possible duplicate of [ngIf - else vs two ngIf conditions](https://stackoverflow.com/questions/44682495/ngif-else-vs-two-ngif-conditions) – santosh singh Feb 08 '18 at 14:53
  • 1
    The main benefit I get from using the `else` syntax is that the template code is less repetitious. From a execution standpoint, I would think the if/else statement would be faster since it's only one evaluation versus two. Someone please correct me if I'm wrong. – Brandon Taylor Feb 08 '18 at 14:54
  • Indeed it is a duplicate of https://stackoverflow.com/questions/44682495/ngif-else-vs-two-ngif-conditions, could not find this before my apologies – Tonio Feb 08 '18 at 14:57
  • 1
    Duplicate question is closed and doesn't allow new answers to be added, so it shouldn't be marked as a duplicate. – Estus Flask Feb 08 '18 at 14:58

1 Answers1

1

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565