What is the usage of Angular 8 ngIf Directive?

The Angular 8 ngIf directive is a structural directive that is used to add or remove HTML elements according to the expression. The expression must return a Boolean value true or false. You can see the functioning of nglf directive clearly. If the expression is false, then the element is removed. Otherwise, the element is inserted. It is similar to the ng-if directive of AngularJS.

In Angular 8, as well as in other versions of Angular, the ngIf directive is used for conditionally rendering or removing an element from the DOM based on a specified condition. It is often employed to control the visibility of elements in the user interface.

Here’s a brief explanation of how ngIf works:

  1. Condition Evaluation:
    • The ngIf directive takes an expression as its input. This expression is evaluated, and if it resolves to true, the associated element is rendered in the DOM. If it resolves to false, the element is removed from the DOM.
  2. Usage Example:
    • In an Angular component template, you might use ngIf like this:
      html
      <div *ngIf=”user.isAdmin()”>
      This content is displayed if the user is an admin.
      </div>
    • In this example, the content within the <div> will only be displayed if the isVisible property in the component resolves to true.
  3. Dynamic Content:
    • You can use ngIf with dynamic conditions based on properties, methods, or expressions in your component.
      <div *ngIf=”user.isAdmin()”>
      This content is displayed if the user is an admin.
      </div>
  4. Else Clause:
    • Additionally, ngIf can be used with an else clause to specify content that should be rendered when the condition is false.
      html
      <div *ngIf=”isLoggedIn; else guestTemplate”>
      Welcome, {{ username }}!
      </div>
      <ng-template #guestTemplate>
      Please log in to access this content.
      </ng-template>
      In this example, if isLoggedIn is true, it will display a welcome message; otherwise, it will display a message prompting the user to log in.

The ngIf directive is a powerful tool for creating dynamic and responsive user interfaces in Angular applications