ngIf Directive

The ngIf directive is a structural directive in Angular that allows you to add or remove an element from the DOM based on a condition. It works by adding or removing a DOM element depending on the truthiness of an expression.

Here are two examples of how you can use the ngIf directive:

<div *ngIf="showElement">
  This element will be displayed if showElement is truthy.
</div>

In the example above, the ngIf directive is used to conditionally render a div element based on the value of showElement. If showElement is truthy (e.g. true), the div element will be added to the DOM. If showElement is falsy (e.g. false), the div element will be removed from the DOM.

You can also use the ngIf directive with an else clause, like this:

<div *ngIf="isLoading; else loadingTemplate">
  This element will be displayed while isLoading is truthy.
</div>

<ng-template #loadingTemplate>
  <div>
    This element will be displayed while isLoading is falsy.
  </div>
</ng-template>

In this example, the ngIf directive is used to conditionally render a div element while isLoading is truthy. The else clause specifies a template that will be used to render an alternate element while isLoading is falsy.

You can use the ngIf directive in Angular whenever you want to add or remove an element from the DOM based on a condition. Some common scenarios where you might use ngIf include:

  • Hiding or showing elements based on user permissions or authentication status
  • Rendering different elements based on the state of a form or input field
  • Displaying a loading spinner while data is being retrieved from an API
  • Showing a message to the user when a list is empty

Here is an example of using the ngIf directive to show a loading spinner while data is being retrieved from an API:

<div *ngIf="isLoading">
  <mat-spinner></mat-spinner>
</div>

In this example, the ngIf directive is used to conditionally render a loading spinner element while isLoading is truthy. When isLoading becomes falsy (e.g. false), the loading spinner element will be removed from the DOM.