ngIf Directive

The ngIf Directives is used to add or remove HTML Elements according to the expression. The expression must return a Boolean value. If the expression is false then the element is removed, otherwise element is inserted. It is similar to the ng-if directive of AngularJS.

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 ngIf directive does not hide the DOM element. It removes the entire element along with its subtree from the DOM. It also removes the corresponding state freeing up the resources attached to the element.

      The *ngIf directive is most commonly used to conditionally show an inline template. See the following example:

      @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;  
        
        } 

          Comments

          Leave a Reply

          Your email address will not be published. Required fields are marked *