Angular *ngIf and an example

The angular, we can control the display of blocks of elements with the help of ngIf condition.

Syntax *ngIf directive:
The *ngIf directive adds and removes elements in the DOM, based on the Boolean result of an expression.

<div *ngIf="condition">Render content when condition is true.</div>

In this example, we will demonstrate two example on *ngIf directive

  1. We will display the div element content on a page only when if the condition showMore variable is true.
  2. We can display the div element content through a toggle button.
angular *ngIf example

Add the following line of app.component.html

<div class="container">
  <h1 hoverer>Hover over me</h1>

<h3>Hello everyone !</h3>
<h3>My name is {{ emp.fname }} {{ emp.lname }}</h3>
<button (click)="moreInfo()">More Details</button>
<div *ngIf="showMore === true">
  <h3>I live in {{}}</h3>
<button (click)="showDiv = !showDiv">Toggle Me</button>
<div *ngIf="showDiv" style="color:white; background-color:blue; width:25%">
  Content 1
<div *ngIf="showDiv" style="color:white; background-color:red; width:25%">
  Content 2

Add the following line of app.component.ts

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  public emp = {fname: 'Happy', lname: 'Singh', city: 'Delhi'};

  public showMore = false;

    this.showMore = true;

Check how to use *ngIf and else in Angular applications using ng-template directive. You can read more information on *ngIf structure directive in Angular official documentation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top