Angular 7|8 ngIf, ngIf else, ngIf then Example

In this tutorial, I show you how to use Angular 8 ngIf directive with lots of examples. We also see the ngIf, ngIf else, ngIf then examples.
We can use ngIf directive to show or hide parts of our angular application.
Check out Angular 7|8 ngFor Example tutorial

Video

This tutorial has explained in below video tutorial on YouTube. Subscribe to our youtube channel for future video updates.

NgIf Directive

From official documentation - ngIf is a structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank.
In the previous tutorial, we have developed an Angular 8 App using Angular 8 Hello World Example Tutorial and we will continue using same Angular 8 app to demonstrates the usage of Angular 8 ngIf directive with examples.

Create an Angular Component - NgifComponent

Let's create NgifComponent in an existing angular8-helloworld-example-tutorial project with the following command:
C:\Angular\angular8-helloworld-example-tutorial\src\app> ng g c ngif
CREATE src/app/ngif/ngif.component.html (19 bytes)
CREATE src/app/ngif/ngif.component.spec.ts (614 bytes)
CREATE src/app/ngif/ngif.component.ts (261 bytes)
CREATE src/app/ngif/ngif.component.css (0 bytes)
UPDATE src/app/app.module.ts (798 bytes)

ngif.component.ts - NgifComponent

The ngif.component.ts file defines the logic associated with NgifComponent. Let's add the following content to NgifComponent:
import { Component } from '@angular/core';

@Component({
  selector: 'app-ngif',
  templateUrl: './ngif.component.html',
  styleUrls: ['./ngif.component.css']
})
export class NgifComponent {

  show: boolean = true

  user = {
    id : 1,
    name: "Ramesh"
  };

  a = true;
  b = false;

  showActions = true;

  users = [{
    id: 100,
    firstName: "Ramesh",
    lastName: "Fadatare",
    emailId: "ramesh@gmail.com"
  },
  {
    id: 101,
    firstName: "Tony",
    lastName: "Stark",
    emailId: "tony@gmail.com"
  }, {
    id: 100,
    firstName: "Tom",
    lastName: "Cruise",
    emailId: "tom@gmail.com"
  }];
}

ngif.component.html - ngIf Directive Examples

The ngif.component.html file defines the HTML template associated with the NgifComponent. Refer the comments in this file are self-descriptive. Replace ngif.component.html file with the following content in it -
<div class="container">
  <h1>ngif Examples</h1>
  <!-- ngIf - Show this all the time -->
  <b>ngIf - Show this all the time</b>
  <p> *ngIf="show">Show this only if "show" is true</p>

  <!-- ngIf - Avoiding "Cannot read property of undefined" errors -->
  <b>ngIf - Avoiding "Cannot read property of undefined" errors</b>
  <p *ngIf="user">
    {{user.name}}
  </p>

  <!-- ngIf - Logical NOT (!) example -->
  <b>ngIf - Logical NOT (!) example</b>
  <p *ngIf="!show">
    Show this only if "show" is NOT true
  </p><br>

  <!-- ngIf - Logical AND (&&) example -->
  <b>ngIf - Logical AND (&&) example</b>
  <p *ngIf="a && b">
    Show this only if a AND b are true
  </p><br>
  <!-- ngIf - Logical OR (||) example -->
  <b>ngIf - Logical OR (||) example</b>
  <p *ngIf="a || b">
    Show this only if a OR b is true
  </p><br>

  <!--  ngIf - Working with "else" Examples -->
  <b> ngIf - Working with "else" Examples</b>
  <div *ngIf="show; else notShow">
    <p>
      Show this only if "show" is true
    </p>
  </div>

  <ng-template #notShow>
    <p>
      Show this only if "show" is not true
    </p>
  </ng-template>

  <!-- NgIf with "then" example -->
  <b>NgIf with "then" example</b>
  <ng-template *ngIf="show;then showBlock; else notShowBlock">
  </ng-template>

  <ng-template #showBlock>
    <p>
      Show this only if "show" is true
    </p>
  </ng-template>

  <ng-template #notShowBlock>
    <p>
      Show this only if "show" is not true
    </p>
  </ng-template>

  <!-- ngIf and ngFor with Table example -->
  <b>ngIf and ngFor with Table example</b>
  <table class="table table-striped">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Email</th>
            <th *ngIf="showActions">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let user of users">
            <td>{{user.firstName}}</td>
            <td>{{user.lastName}}</td>
            <td>{{user.emailId}}</td>
            <td *ngIf="showActions">
                    <button>Delete</button>
                    <button>Update</button>
            </td>
          </tr>
        </tbody>
      </table>
</div>

Working with "else"

The angular ngIf directive does also allow us to declare an else-block. This block is shown if the statement defined in the main block happens to be false.
 <!--  ngIf - Working with "else" Examples -->
  <b> ngIf - Working with "else" Examples</b>
  <div *ngIf="show; else notShow">
    <p>
      Show this only if "show" is true
    </p>
  </div>

  <ng-template #notShow>
    <p>
      Show this only if "show" is not true
    </p>
  </ng-template>

Working with ngIf "then"

In some rare cases, it might be useful to have the ngIf directive from its actual result-block. This would enable us to swap the result of the block out on the fly, by just referencing another ng-template.
For that reason, angulars' ngIf directive also has a then property.
<!-- NgIf with "then" example -->
  <b>NgIf with "then" example</b>
  <ng-template *ngIf="show;then showBlock; else notShowBlock">
  </ng-template>

  <ng-template #showBlock>
    <p>
      Show this only if "show" is true
    </p>
  </ng-template>

  <ng-template #notShowBlock>
    <p>
      Show this only if "show" is not true
    </p>
  </ng-template>

app-routing.module.ts - Add Entry Routing

Let's add an entry in app-routing.module.ts file :
 {path: 'ng-if', component: NgifComponent}
Here is the complete code:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HelloWorldComponent } from './hello-world/hello-world.component';
import { NgforComponent } from './ngfor/ngfor.component';
import { NgifComponent } from './ngif/ngif.component';

const routes: Routes = [
  {path: '', component: HelloWorldComponent},
  {path: 'hello-world', component: HelloWorldComponent},
  {path: 'ng-for', component: NgforComponent},
  {path: 'ng-if', component: NgifComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Output

Hit this link in browser: http://localhost:4200/ng-if
Check out complete Angular 8 tutorial with examples - Angular 8 Tutorial with Examples.
The source code of this tutorial available on my GitHub Repository.

Comments