Consider the following code sample:
<div *ngIf="condition; else elseBlock">
<!-- markup here -->
</div>
<ng-template #elseBlock>
<div>
<!-- additional markup here -->
</div>
</ng-template>
Another way I can achieve the same functionality is:
<div *ngIf="condition">
<!-- markup here -->
</div>
<div *ngIf="!condition">
<!-- additional markup here -->
</div>
I want to know specific reasons for which of these two ways should be used and why?
Using else lets you avoid writing the condition twice, which could be a source of bugs, so I would use that preferentially. You can also put the else template down at the bottom of your template if you so choose, which can make the template easier to read.
If you are unwrapping an observable with the async
pipe, then it is much easier to write
<div *ngIf="myItems$ | async as myItems; else noItemsYet">
than to add another <div *ngIf="!(myitems | async)">
, which would also force Angular to create another internal subscription.
Those voting to close this question as a matter of opinion are misguided. The fact that people might have different opinions on something does not mean that there are not valid points that are worth putting forward.
If using else
was a matter of mere preference, I doubt the Angular developers would have prioritized it for Angular 4 as they did.
As @Ishnark points out, there may be performance implications as well.
The first solution is better. Although both achieve the same thing, the first is cleaner and easier to follow logically.
You only do one check with the first solution. This is a good solution because:
- It takes time to evaluate a condition.
- By using else, you only have to check once. In your second solution you check if a condition is met (which takes time), and then you check if the not of the same condition is met.
- Using else allows you to have an action to do in the case that somehow neither of the conditions are met.
EDIT: See @toazaburo's answer, which addresses unsafeness.