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?
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:
EDIT: See @toazaburo's answer, which addresses unsafeness.
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 writethan 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.