Angular ngIf Directive

In the previous article, we’ve learned about the ngFor directive. In this article, we’re going to learn about the ngIf directive, and it’s working.

What is Angular ngIf Directive?

The ngIf is basically a built-in template directive used to display HTML elements conditionally into the View. It’s the same as if statement in any programming language. Of course, we know that HTML is not a programming language, but analogically, this makes HTML a programming language and makes developer’s work easy.

Let’s see the syntax of the ngIf directive.

<h1 *ngIf="display">
  Errorsea is displayed
</h1>

The display is the property that is declared in the TypeScript file and set to true.

Example 1

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  display=true;
}

Output:

angular ngIf directive example 1

Similarly, we also have else block as well. So let’s see the implementation of the else block with the if block as well.

<h1 *ngIf="display; else elseBlock">
  Errorsea is displayed
</h1>
<ng-template #elseBlock>
  <h1>
    Errorsea is hidden
  </h1>
</ng-template>
  • Here, <ng-template> is an Angular specific HTML tag.
  • #elseBlock is the reference variable that holds the reference of the template.
  • First, it checks the if condition; if it’s true, it’ll display Errorsea is displayed e. to the element to which ngIf is attached.
  • If the condition is false Angular checks for the else statement; therefore, the element will be displayed that is attached to.

Example 2

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  display = false;
}

Here we kept the display value as false, hence elseBlock should be displayed into the View.

Output:

angular ngIf directive example 2

Conclusion

We hope this article has helped clear your concepts on the ngIf directive, and it’s working. In the next article, we’ll learn one more directive of Angular, i.e., ngSwitch. After that, we’ll move on to some other important topics of Angular.

Read Next: Angular ngSwitch Directive

Leave a Reply

Your email address will not be published. Required fields are marked *