Home >>Angular8 Tutorial >Angular8 ngIf Directive

Angular8 ngIf Directive

Angular8 ngIf Directive

According to the expression, the ngIf directive is used to add or delete HTML elements. The expression has to return a value in Boolean. Unless the expression is false then the element will be removed, the element will be added otherwise. This is similar to AngularJS 'ng-if directive.

ngIf Syntax

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

The *ngIf directive form with an "else" block


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

The DOM element isn't hidden by the ngIf directive. This removes the entire feature from the DOM, along with its subtree. It also removes the corresponding state freeing up the allocated resources to the item.

Most widely used for conditionally displaying an inline template is the * ngIf command. See the example below:


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

Same template example 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">Text to show</div>  
    <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>  
`  
})  
export class NgIfElse {  
  show: boolean = true;  
}  


No Sidebar ads