Angular ngIf,else tutorial with examples

Angular ngIf,else tutorial with examples

In this tutorial, we are going to learn about how to use ngIf directive to conditionally show or hide elements in angular.

*ngIf Directive

The *ngIf directive binds to an expression, if the expression value is evaluated to true then the element is added to dom else the element is not added to the dom.

This example shows you how to use *ngIf directive.

app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  isActive = true;
}
app.component.html
<div>
    <h1 *ngIf="isActive">Hello angular</h1></div>

In the above code,we have added *ngIf="isActive" to h1 element and isActive property is true so that we can see h1 element in the dom.

Note: Asterisk * is important to add in front of ngIf directive.

If we want to hide the h1 element, we can do it by adding a ! negation sign in front of isActive property.

app.component.html
<div>
    <!-- you can't see me -->
    <h1 *ngIf="!isActive">Hello angular</h1></div>

Extending *ngIf directive with else statement

Instead of showing and hiding the same element we can render the different element if our provided expression is evaluated to false by using else statement.

Example:

<div>
    <h1 *ngIf="isActive else notActive">Hello angular</h1>
    <ng-template #notActive><h1>Hello React</h1></ng-template></div>

Here we included else notActive to *ngIf directive so that we can use #notActive as a reference variable to show the different element if our provided expression evaluates to false.

Why we used ng-template?

The ng-template is an angular element to render the HTML, by using ng-template angular replaces the provided element with a comment and only render the element when it’s needed, like in our example ng-template only renders the element when an else statement is active.

If you’re not comfortable with this else syntax, we can also achieve the same (if, else) thing using ! negation sign.

Example:

<div>
    <h1 *ngIf="isActive">Hello angular</h1>
    <h1 *ngIf="!isActive">Hello React</h1>
</div>

In the above code, the first h1 element will render when an isActive is true and second h1 element will render when a isActive is not true, it means (false or else) case.