Angular 8 ngIf Directive

To add or remove HTML Elements according to the expression, such that the expression returns a Boolean value, the ngIf Directive is used. The element is inserted if the expression is true or else it removes the element. The ngIf Directive of Angular 8 is similar to the ng-if directive of AngularJS.

Syntax 1:

<p *ngIf="condition">  
    the condition is true and ngIf is true.  
</p>  
<p *ngIf="!condition">  
    the condition is false and ngIf is false.  
</p>

Syntax 2: The *ngIf directive form with an “else” block.

<div *ngIf="condition; else elseBlock">  
Content to render when the condition is true.  
</div>  
<ng-template #elseBlock>  
Content to render when the condition is false.  
</ng-template>

Without hiding the DOM element, the entire element along with its subtree from the DOM is removed by the ngIf directive. It also frees up the resources attached to the element, by eliminating the corresponding state. To conditionally show an inline template, the *ngIf directive is most preferred.

Example 1:

@Component({  
  selector: 'ng-if-simple',  
  template: `  
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>  
    show = {{show}}  
    <br>  
    <div *ngIf="show">Hello World</div>  
`  
})  
export class NgIfSimple {  
  show: boolean = true;  
}

Example 2: with else block:

@Component({  
  selector: 'ng-if-else',  
  template: `  
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>  
    show = {{show}}  
    <br>  
    <div *ngIf="show; else elseBlock">Hello World</div>  
    <ng-template #elseBlock>I am hidden</ng-template>  
`  
})  
export class NgIfElse {  
  show: boolean = true;  
}