Structural directives-NgIf Null Check

For the null value of the expression assigned to NgIf, it does not add the element tree in DOM. Therefore, it is useful when accessing the property from the object to avoid errors. For the demo we will use the following class.

NgIf can be used in different ways.

customer.ts

export class Customer {
    constructor(public id: number, public name: string) {
    }

}

We import it into our component as follows.

import {Customer} from './customer';  

We will now define two variables of class Employee type in the component as shown below.

customer1 = new Customer(1, 'Ajeet');
customer2 : Customer;  

Here we will notice that customer1 has been instantiated but customer2 has not been instantiated.

Now Use the following code in app.component.html file.

app.component.html

<h3>NgIf Null Check</h3>
<div *ngIf="customer1">
    Id:{{customer1.id}} Name: {{customer1.name}}
  </div>
  <div *ngIf="customer2">
    Id:{{customer2.id}} Name: {{customer2.name}}
  </div>  

And Use the following code in app.component.ts file.

app.component.ts

import { Component } from '@angular/core';
import { Customer } from './customer';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  customer1 = new Customer(1, 'Ajeet');
  customer2: Customer;

}

This will be the output of the above code.

Structural-SahosoftTutorials-NgIf-Null-Check