Angular

Angular ngIf else : Practical Example and Best Practices


Introduction

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.

Basic Usage of *ngIf else

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>

Explanation

  • isLoggedIn: This is a boolean property specified in your individual element.
  • else loggedOutTemplate: Shows another template to render if isLoggedIn is false.
  • <ng-template>: The content which is to replace the original content in case the latter is not desired by the user. 

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>

Best Practices

  • Keep Logic in the Component: If you need to write complex conditions you should do this in the component rather than in the template to make the code of the template clear.
  • Use Descriptive Template References: It is recommended to provide a meaningful name to your ng-template references to keep things more understandable.

Conclusion

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

Angular

Related Center Of Excellence