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?
According to Angular documentation, ngIf is an Angular (v +2) directive , however, ng-if is an AngularJS (v 1. x) directive. as also mentioned by @rcoro in comments.
The NgIf directive is used when you want to display or remove an element based on a condition. If the condition is false the element the directive is attached to will be removed from the DOM .
We're prefixing these directive names with an asterisk (*). The asterisk is "syntactic sugar". It simplifies ngIf and ngFor for both the writer and the reader. Under the hood, Angular replaces the asterisk version with a more verbose form.
A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.
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:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With