Reputation: 4661
I'm trying to understand the difference between ng-if
and *ng-if
, but they look the same to me.
Is there a difference that I should keep in mind choosing one over the other and when to use these directives?
Upvotes: 43
Views: 35804
Reputation: 11
Currently in Angular we use ngIf instead of ng-if so considering the difference here we can implement it rather this way:
In case of *ngIf - <div *ngIf="condition">Content to render when condition is true.</div>
In case of ngIf - <ng-template [ngIf]="condition"><div>Content to render when condition is true.</div></ng-template>
You can find this detailed on angular.io>API references
Upvotes: 0
Reputation: 121
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.
Upvotes: 5
Reputation: 658027
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.
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>
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>
Upvotes: 16
Reputation: 202306
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:
Upvotes: 54