{

Angular ngIf examples


Angular ngIf tutorial and eample

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.

Syntax

<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. The 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 always shown to the 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 the following operators

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

Logical operators example Logical operators are used to applying 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 to 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 to true if the conditional expression is evaluated to false

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

Comparison operator example Following is an example to check 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.

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

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

to make it conditional expression as async, 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 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';

@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 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>
    </div>

No provider for TemplateRef in Angular

ngIf directive is applied to an HTML div element, bool value initialized in typescript component, show the content is output to the 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 an angular directive that you will not automatically use in your application.

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

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 the conditional expression was evaluated with Observable async calls, but the template uses conditional expression without an async pipe symbol.

use async pipe to conditional expression in ngIf directive

<div *ngIf="{variable$|async}">content</div>
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.