How To Use *ngIf else In Angular 12 | ng-template

The *ngif else in Angular allows us to add or remove DOM Element based on the evaluation of the expression. We can use a conditionally rendering with component, directive, and HTML elements. If the condition is true the element will be rendered.

In Angular, we can use *ngIf in different ways.so let’s start by exploring the ways with example.

In this example, we will use *ngIf condition. we want to render elements only when the condition is true.

 <div *ngIf="isAdminRole">
      <div class="row">
        <span>User Id</span>
        <span>Admin</span>
      </div>
      <div class="row">
        <span>User Role</span>
        <span>Administrator</span>
      </div>
</div> 

In the above code snippet, we are using the *ngIf condition to check isValidate variable to display user details. 

Use of *ngIf and else with example

Sometimes we have to display a custom message or HTML element based on condition. In this case, we can use else condition with ng-template in Angular. 

<div *ngIf="isAdminRole else tplNotValid"">

  <div class="row">
    <span>User Id</span>
    <span>Admin</span>
  </div>
  <div class="row">
    <span>User Role</span>
    <span>Administrator</span>
  </div
  >
</div>

<ng-template #tplNotValid>
  <h4>user is not authorized to access this resource </h4>
</ng-template> 

use of *ngIf then and else with example

We can also use the then syntax with else using the ng-template. In the below example, we are using then syntax, If the condition is true, the then template block will render. If false, then the else template Block will render.

<ng-container
  *ngIf="isAdminRole; then adminSection; else userSection">
</ng-container>

<ng-template #adminSection>
  <div>
    Welcome back, Admin.
  </div>
</ng-template>

<ng-template #userSection>
  <div>
    Welcome back, User.
  </div>
</ng-template> 
  • Post category:Angular
  • Reading time:3 mins read