Tonio
Tonio

Reputation: 5044

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 ?

Upvotes: 3

Views: 1236

Answers (1)

Estus Flask
Estus Flask

Reputation: 223084

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.

Upvotes: 1

Related Questions