Using the ngIf directive to add or remove elements from the DOM based on a condition

Using the ngIf Directive in Angular

The ngIf directive is a powerful tool for adding or removing elements from the DOM in an Angular template. It allows you to specify a condition, and if that condition is true, the element will be displayed. If the condition is false, the element will be removed from the DOM.

Example

Here's a simple example of how to use ngIf in an Angular template:

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

In the component class, you can set the showElement property to true or false to control whether or not the element is displayed.

        
          export class MyComponent {
            showElement = true;
          }
        
      

You can also use an else clause with ngIf to specify a template to be displayed if the condition is false:

        
          <div *ngIf="showElement; else elseTemplate">
            This element will be displayed if the showElement property is true.
          </div>
          <ng-template #elseTemplate>
            This element will be displayed if the showElement property is false.
          </ng-template>
        
      

The ngIf directive is a great way to dynamically add or remove elements from the DOM based on a condition. It's a simple yet powerful tool that can be used in many different scenarios in your Angular app.

Comments