In Angular, conditional rendering is considered to be a vital tool for developing interactive and or reactive web applications. The *ngIf directive is one of the most common utilities for this, because it lets the developer use a condition to include or exclude elements from the DOM tree. But what if for some reason you have to use a different template when the condition equals to false? This is where ngIf else comes into play this makes it easier when we want to compare more than two values.
Although *ngIf may be used together with the else keyword to present another template when the initial condition is negative. Here’s a basic syntax example:
<div *ngIf="isLoggedIn; else loggedOutTemplate">
<p>Welcome back, user!</p>
</div>
<ng-template #loggedOutTemplate>
<p>Please log in to continue.</p>
</ng-template>
Example with More Complexity
Suppose you want to show different content based on a user’s role:
<div *ngIf="userRole === 'admin'; else userTemplate">
<p>Welcome, Admin! You have full access.</p>
</div>
<ng-template #userTemplate>
<p>Welcome, user. Your access is limited.</p>
</ng-template>
With the help of Angular directive *ngIf else we can easily handle the conditional rendering with Place Holder. It improves your reception on how you will be able to develop appealing and adaptive user interfaces.
In your next Angular project, you should try using *ngIf else: it enhances the user experience!
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
0