Angular ngIf code examples

ngIf is a directive in Angular used to show or hide the HTML elements of a DOM tree.

It is similar to if conditional expression in a programming language like java or javascript.

The following topics are covered in this post:

  • ngIf standard directive in Angular
  • use ngif then else template in Angular
  • Usage of logical and comparison 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.

ngIf evaluates expressions as true or false. If this is true, an element will be added to the DOM Tree. If false, elements will be removed from the DOM tree.


<element *ngIf="(conditionalexpression)" />

The same can be rewritten using template syntax

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

element is a valid angular custom element or HTML element. Examples are p, div, span, etc…

*ngIf is a keyword applied to the element.

a conditional expression is a JavaScript expression always evaluated to Boolean value using synchronous or asynchronous calls.

Basic ngIf example

It is a simple variable declared which is true, and content is always shown to the user.

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

  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 the following operators

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

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

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

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

Comparison operator example Following is an example to check the role type

the role is a variable declared in the typescript component as follows

let role: string;

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

<div *ngIf="role==='user'">
User dashboard
Admin dashboard
<div *ngIf="role==='superadmin'">
SuperAdmin dashboard

Angular if then else template

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

<div *ngIf="expression ; else elseContent">
  This will be displayed to user when expression is true
<ng-template #elseContent
  >This is displayed when the expression is false.</ng-template

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 the expression is true.</ng-template
<ng-template #elseTemplate
  >This is shown when the expression is false.</ng-template

example if the role is admin, Admintemplate is loaded into the DOM tree, else user template is added to the 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

Sometimes we want to check asynchronous values, which means when a form is loaded with default values, the Once asynchronous call is finished, and the expression is updated with a new value over time.

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

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

In the below code, isLoaded initial value is false, which will not display user data Once an API call is made returns the Observable user’s 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";

  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
export class AppComponent {
  public isLoaded: boolean = false;
  users: any[];
  ngOnInit() {
  private getAPIData() {
      (response) => {
        if (response) {
          this.isLoaded = true;
          this.users = response;
      (error) => {
        this.users = null;

Angular ngIf null check example

null check in the 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 if a null or list is empty.

In typescript, the 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>

No provider for TemplateRef in Angular

ngIf directive is applied to an HTML div element, bool value initialized in the typescript component shows the content is output to the browser.

Please note that ngIf is prefixed with *, if * is omitted, The error comes for the 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 an angular directive that you will not automatically use in your application.

To use directives, CommonModule is required to import into your application.

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

  imports: [CommonModule],
  declarations: [],
  bootstrap: [],
export class AppModule {}

Expression has changed after it was checked

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

use an async pipe to conditional expression in ngIf directive

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