What is the difference between ng-if and *ng-if in angular2

ngIf is the directive. Because it's a structural directive (template-based), you need to use the * prefix to use it into templates.

*ngIf corresponds to the shortcut for the following syntax ("syntactic sugar"):

<template [ngIf]="condition">
  <p>
    Our heroes are true!
  </p>
</template>

Equivalent to:

<p *ngIf="condition">
  Our heroes are true!
</p>

See this doc for more details:

  • https://angular.io/docs/ts/latest/guide/structural-directives.html

To keep it simple, in the latest angular versions to date, for example when we use *ngIf like below.

<div *ngIf = "condition">
//code here
</div>

Now, the above code is actually rendered by angular as below:

<ng-template [ngIf]="condition">
<div>
//code here
</div>
</ng-template>

Hence we can either use *ngIf directly as a structural directive or we can use [ngIf] as attribute directive but with a ng-template. Hope this makes things more clearer.


The difference is that both are not supported in Angular2 ;-) at least in current versions - it should be *ngIf or ngIf.

Structural directives can be used with explicit <template> tags or implicit <template> tag. For the implicit version a * is required to indicate it is a structural directive.

explicit

<template [ngIf]="someExpr">
   <div>content</div>
</template>

or since 2.0.0 preferred

<ng-container *ngIf="someExpr">
   <div>content</div>
</ng-container>

implicit

<div *ngIf="someExpr"></div>

Usually you will use the implicit version because it is more concise.

When to use the explicit version?

There are use cases where the implicit version doesn't work.

  • If you want to apply more than one structural directive like ngFor and ngIf which is not supported, then you can use the explicit form for one of these.

Instead of this invalid syntax

<div *ngFor="let item of items" *ngIf="!item.hidden"></div>

you can use

<ng-container *ngFor="let item of items">
  <div *ngIf="!itemHidden></div>
</ng-container>
  • If you want to apply the structural directive to more than one element

For example you want to list several items with name and price per row

<tr>
  <td *ngFor="???">item.name</td>
  <td>item.price</td>
</tr>

<tr>
  <ng-container *ngFor="let item of items">
    <td>item.name</td>
    <td>item.price</td>
  </ng-container>
</tr>