Tuesday 28 February 2017

ng-if in angular 2

Angular js 1 ng-if is pretty straight forward to use. Let us check how it is in angular js 2.


 <div ng-if="showSelected">Hey I am in</div>

ng-if directive removes or adds portion of dom. If ng-if value is false then it won't show at all in the dom.

How it is in Angular js 2.


<div *ngIf="showSelected">Hey I am in</div>

There is no major changes for ng-if in angular js 2.

For template

<template [ngIf]="showSelected"><div>Hey I am in</div></template>  

Angular js 2 ngif behavior also same as angular js one except the syntax changes. It also removes or adds from dom depends on the status true/false, otherwise a clone of the element is added to the dom.

If interested please check component code as well.

  selector: 'my-app',
  template: `<div>
           <button (click)="ShowButton()">Show Result</button>
           <button (click)="HideButton()">Hide Result</button>
           <div *ngIf="showSelected">Result Found</div>
export class AppComponent {
    showSelected : boolean;
        this.showSelected = false;     
        this.showSelected = true;
        this.showSelected = false;

Related Post

1. ng-repeat in angular js 2

2. Angular 2 filter using pipe concept

3. ng-click in angular js 2


  1. Can you please add the component code as well