Open In App

How to use *ngIf else in AngularJS ?

Last Updated : 05 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression evaluates to true it runs/displays the template given in the “then” clause. Or when the expression evaluates to false it displays the template given in the “else” clause. If there is nothing in else clause, it will by default display blank.

Syntax:

ngIf with an "else" block




<div *ngIf="condition; else elseStatement">
    when condition is true.
</div>
<ng-template #elseStatement>
    when condition is false.
</ng-template>
<!--It can be seen that the else 
    clause refers to ng-template,
    with the label #elseStatement -->


It internally creates two <ng-template>, one for “then” statement and another for “else”. So when the condition is true for ngIf, the content of the unlabelled <ng-template> gets displayed. And when false, the labelled <ng-template> runs.

Approach:

  1. As we know, ngIf else statement works on a variable that has a boolean type. Create an angular app and move to src/app. First, we need to define a variable say “check” in app.component.ts with a value true or false.




    <!-- Define a variable say "check" with
         value true/false in app.component.ts -->
    import { Component } from '@angular/core';
      
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
      
    export class AppComponent {
      check:boolean = true;
    }

    
    

  2. After defining a variable, move to app.component.html and create two divisions using bootstrap classes. Move into the angular app and write command npm install bootstrap. The first division is for the “true” condition and the one inside <ng-template> is for the false condition. We have declared check to be true so we get a green division saying condition true. If the check was false, a red division saying condition false would be displayed.




    <!-- *ngIf else -->
    <div class="container-fluid">
        <div class="row bg-success 
                text-light h1 justify-content-center
                align-items-center" *ngIf="check;
                else elseStatement" 
                style="height:150px">Condition true
        </div>
      
      <ng-template #elseStatement>
        <div class="row bg-danger
                text-light h1 d-flex 
                justify-content-center align-items-center"
                style="height:150px">Condition false
        </div>
      </ng-template>
    </div>

    
    

Output:

Output:

Advantages:

  • Programming language’s "if" block supports logical operators so it does "ngIf". It has support for all the logical operators like AND, OR, NOT, etc.
  • ngIf helps to avoid can’t read property error of undefined. Suppose there is a bound property called “student”. We are trying to access the “name” sub-property of the student which has value “Santosh”. If the student is null, it will return error undefined. So if we check for null before accessing sub-property, we will prevent error using *ngIf.




    <!--This may error-->
    <div>
      {{student.name}}
    </div>
      
    <!--check using ngIf-->
    <p *ngIf="student">
      {{student.name}}
    </p>

    
    

    Output:

    Santosh
  • ngIf vs Hidden: You might wonder why do we have to use ngIf when we have hidden attribute in HTML5. Yes, they do the same work but there is still a difference. The hidden attribute hides the selected element from the DOM but the element still exists in the DOM. Whereas ngIf gets rid of the selected part from the DOM. It doesn’t intervene with CSS.




    <!--check is defined in component.ts 
        with value true (boolean)-->
    <div [hidden]="!check">
      Show this only if "check" is true
    </div>

    
    

    Output:

    Show this only if "check" is true


Similar Reads

How to use ngIf without an extra element in Angular2?
In order to use *ngIf without an extra element in Angular 2+, we can use either &lt;ng-container&gt; or &lt;ng-template&gt;But in many cases, &lt;ng-container&gt; is recommended.The best scenario regarding the usage of with *ngIf without an extra element is mentioned below. app.component.ts: import { Component } from '@angular/core'; @Component({ s
1 min read
Use of *ngIf and *ngFor Directives in Angular
Angular is a very popular framework for building scalable web applications. It provides many features and tools to make the development process smooth. Two important directives in Angular are *ngIf and *ngFor. *ngIf is used to conditionally render HTML elements, while *ngFor is used to iterate over a collection of data. In this article, we will lea
5 min read
Angular 10 NgIf Directive
In this article, we are going to see what is NgIf in Angular 10 and how to use it. The ngIf Directive in Angular10 is used to remove or recreate a portion of HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM. Syntax: &lt;li *ngIf='condition'
2 min read
JavaScript if else else if
The JavaScript if, else, and else if statements are part of the conditional statements available in JavaScript. These conditional statements are used to execute a particular block of code based on the passed condition. It will execute the code statements only if the condition turns to true. We have the following conditional statements available in
3 min read
AngularJS ng-class if-else Expression
In the AngularJS framework, Conditional statements, like if-else expressions, are a feature that helps many web developers like us to apply different conditions in AngularJS applications. This can be used with the ng-class directive that allows us to control the styling of the elements based on the change of variables and other user inputs. These i
5 min read
How to use if, else and not statements in Ember.js ?
Ember.js is a framework for web development. It makes the process of development and prototyping faster with its tools. We can create dynamic web pages with it. Based on the dynamic data, we may or may not want to display some data or some UI or modify the UI. So we will learn to use If, Else and Not in an Ember.js application. Create the project S
3 min read
How to use a Custom Service Inside a Filter in AngularJS ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a &lt;script&gt; tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. An Angular service is a broad category that consists of any value, function, or feature that an application
4 min read
AngularJS | How to use ng-idle?
The ng-idle is used to decrease the burden, bandwidth, and workload of an app, website, program, or software. With the help of ng-idle log out the session of inactive users so that our precious data &amp; the workload is getting preserved or to even taunt them to participate more actively. The ng-idle is the module, which is required to respond to
3 min read
What is the use of a double-click event in AngularJS ?
The ng-dblclick event in the AngularJS is useful for the HTML elements for getting the double click event, defined. In case a user wishes to get the function fired or other events when the double click of the HTML elements is done, then this event will be going to be needed. All the elements of the HTML will be going to support it. Basically, the d
2 min read
How to use filter within controllers in AngularJS ?
In this article, we will see how to use the Filter inside the controller using AngularJS. Filters are used to format the value of an expression and display it to the user. It can be used in HTML Previews, Controllers or Services, and directives. AngularJS facilitates many built-in filters, although, we can create &amp; define the custom filters eas
4 min read