Loading
 
What's Next: View All Tutorial →

Ng-click and ng-if in Angular2 (click and *ngIf)

A simple program to explain the ngIf program. *ngIf is the directive statement. Based on the boolean expression response, it show the element in the page. The *ngIf can be added to any html element div, p , form elements , css elements ,etc ...

Published Date: 10/12/2016  Last Modified Date: 10/12/2016    New Post




A simple program to explain the ngIf program.

*ngIf is the directive statement. Based on the boolean expression response, it show the element in the page.

The *ngIf can be added to any html element div, p , form elements , css elements ,etc

Program:

This program has two flag employeeFlag and personFlag, on the button click the particular flag will be enabled, the template html will be updated on the flag changed in the class immediately

Code Snippet:
 
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  
   <button (click)="showEmployee()">Show Employee</button>
    <button (click)="showPerson()">Show Person</button>
    <br><br>
    
    
    
    <div *ngIf="employeeFlag">
    Employee Name: John
    </div>
    <div *ngIf="personFlag">
    Person  Name: David
    </div>
    
    
   
  `
})
export class AppComponent {
  
  employeeFlag :boolean = false; 
  
  personFlag : boolean= false;
  
  showEmployee=function(){
    this.employeeFlag = true;
    this.personFlag = false;
  }
  showPerson= function() {
    this.employeeFlag = false;
    this.personFlag = true;
  }
  
  
  
}
 

Program Execution:


Live program is uploaded in the plunker.

https://plnkr.co/edit/BmlSg8jaEGDnwMyU9RGp?p=preview
 

Program Output:


1. On click of Employee Button
 
Employee Name: John

 
2. On click of Person Button

Person Name: David




 

Example 2:

 
 <p *ngIf="true">True statement will be displayed</p>
    
    <p *ngIf="false">False statement will not be displayed</p>
    
    <p *ngIf="1>1"> 1 is greater than 1 - false</p>
    <p *ngIf="1>=1"> 1 is greater than or equal to 1 - true</p>
    

Output:
 

True statement will be displayed

1 is greater than or equal to 1 - true



 
Awaiting for Administrator approval





Tags: Directive

← Back to list


Related Post




×