Angular tutorial - ngIf then else examples


ngIf is a directive used to hide and show the html elements of a DOM tree. It acts as like a if conditional expression in programming language like java or javascript. This post convers the following things

  • ngIf standard directive in Angular
  • use ngif then else template in Angular
  • Usage of logical and comparision operator
  • NgIf async Observable example
  • ngIf null check usage
  • Common Errors in ngIf template

Angular ngIf directive

ngIf is a directive from CommonModule declared in @angular/common package.

expression in ngIf is true, It add new element to DOM tree. and for false value, remove element from DOM tree

Syntax

<element *ngIf=(conditionalexpression) />

The same can be rewritten using template syntax

<ng-template [ngIf]="expression">
</ng-template>

element is valid angular custom element or html element. The examples are p,div,span etc…

*ngIf is keyword applied to element.

conditional expression is javascript expression always evaluted to boolea value using synchronous or asynchoronous call.

Basic ngIf example

This is simple variable declared which is true, and content always shown to user.

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  bool:Boolean=true;
}

In html template

<div *ngIf="bool">
  Show the element
</div>

ngIf expression example

The expression can contain javascript expressions using following operators

  • Logical operators (&&,|| or !)
  • Comparision operator

Logical operators example Logical operators are used to apply multiple conditions in a expression

In the below example if role is admin or super admin, Button is displayed for edit profile Logical or (||) is evalute to true if one of the expression is true Logical And (&&) is evalute to true if all the conditional expression evaluated to true Logical Not (|) is evalute to true if conditional expression evaluated to false

<button  *ngIf="role === 'admin' || role ==='superadmin'" >Edit profile</button>
<button  *ngIf="role !== 'admin' && role ==='superadmin' && role!=='user'" >Login</button>

Comparision operator example Following is an example to check role type

role is an variable declared in typescript compoent as follows

let role:string;

and === and == operator is used to compare the strings and returns boolean value.

Angular if then else template

This is one more to achieve similar kind of if else conditional block operatios in html templates. expression is evaluated boolean value, if true, then block is added, else block is added to DOM Please note that template variable is declared and referenced in ng-template to load dynamically. ** Syntax**

The same above syntax can be rewritten with if else then directive as follows

<div *ngIf="expression; then thenTemplate else elseTemplate"></div>
<ng-template #thenTemplate>This is shown when expression is true.</ng-template>
<ng-template #elseTemplate>This is shown when expression is false.</ng-template>

example if role is admin, Admintemplate is loaded into DOM tree, else usertemplate is added to DOM tree

<div *ngIf="role==='admin'; then AdminTemplate else UserTemplate">
</div>
<ng-template #AdminTemplate>
Admin Dashboard
</ng-template>
<ng-template #UserTemplate>
User Dashboard
</ng-template>

ngIf async observable usage

Some times we want to check asynchronous values, that means when form is loaded with default values, Once asynchornous call is finished, the expression is updated with new value over time.

to make it conditional expression as asyc, adding pipe with async keyword to expression

<div *ngfor="let user of users$ | async" *ngIf="(isLoaded$ | async)">display user data</div>

In the below code isLoaded initial value is false, which will not dispalyed user data Once API call made returns the Observable users data. Subscribed the observable data using success and error callback in success callback, isLoaded is updated with true Now Browser is displayed with users data.

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
public isLoaded: boolean = false;
users: any[];
ngOnInit() {
  this.getAPIData();
}
private getAPIData() {
  this.APIService.getDatabaseRows().subscribe(
    (response) => {
       if (response ) {
         this.isLoaded = true;
         this.users=response;
       }
    },
    (error) => {
      console.log(error);
      this.users=null;
    }
 );
}
}

Angular ngIf null check example

null check in html template enables not to load the component when there is no data in objects. For example, emailList is an array of objects, To check an null or list is empty .

In typescript, emailList variable holds the array of data, which can be retrieved from API.

let emailList: any[];
    <div *ngIf="!emailList || emailList.length === 0">
        <p>Inbox is empty</p>
    </div>

No provider for TemplateRef

ngIf directive is applied to html div element, bool value initilized in typescript component, show the content is output to browser.

Please note that ngIf is prefixed with *, if * is ommited, The error comes for below code if * is not prefixed

<div ngIf="bool"> show </div>

error is thrown -NullInjectorError: No provider for TemplateRef!

Can’t bind to ‘ngIf’ since it isn’t a known property of ‘div’.

ngIf is angular directive which you will not automatically use in your application.

To use directives, CommonModule is required to import in your applicaiton.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

@NgModule({
  imports:      [  CommonModule ],
  declarations: [  ],
  bootstrap:    [  ]
})
export class AppModule { }

Expression has changed after it was checked

This was an issue when conditional expression evaluated with Observable asyn calls, but template uses conditional expression without async pipe symbol.

use async pipe to conditional expression in ngIf directive

<div *ngIf="{variable$|async}">content</div>
Similar Posts