Angular 7 ngIf Directive

Use of *ngIf directive to change the output conditionally:

Example:

component.ts file:

import { Component, OnInit } from '@angular/core';  
  
@Component({  
  selector: 'app-server2',  
  templateUrl: './server2.component.html',  
  styleUrls: ['./server2.component.css']  
})  
export class Server2Component implements OnInit {  
 allowNewServer = false;  
 serverCreationStatus = 'Server not created.';  
  serverName = 'TestServer';  
  serverCreated = false;  
  
  /*constructor() {  
    setTimeout(() =>{  
      this.allowNewServer = true;  
    }, 5000);  
  }*/  
  
  ngOnInit() {  
  }  
  onCreateServer() {  
    this.serverCreated = true;  
    this.serverCreationStatus = 'Server created with the Name: ' + this.serverName;  
  }  
  OnUpdateServerName(event: Event) {  
    this.serverName = (event.target).value;  
  }  
}  

component.html file:

Server2 is working fine.

Server created with the Name: {{serverName}}

Output:

Now, change the input value and click on the “Add Server” button.

Output:

Explanation:

In the above example, we are using the *ngIf directive to change the condition to display the output accordingly.

The view-source of the output can be checked before and after adding the server to know exactly how a structural directive can change the DOM.

Before adding the server:

After adding the server:

*ngIf directive with an Else condition:

An Else condition can be used with *ngIf directive to display the output if *ngIf is not true.

Example:

//component.html file:

Server2 is working fine.

Server created with the Name: {{serverName}}

No Server is created.

Output:

Now click on the “Add Server” button.

Output:

The reverse case can be checked by using the negation (!) sign.

Example:

component.html file:

Server2 is working fine.

Server created with the Name: {{serverName}}

No Server is created.