Recently I used a *ngIf
directive with an else block in Angular and was wondering why in the Angular docs the examples use a semicolon (<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>
) as this seems to work without the semicolon as well.
Does this have any side effects not to use the semicolon? Or is this just a more cleaner way to code?
On the div tag we added the ngIf directive that would be displayed if the value of toggleOn is false. After that, we added some dummy paragraphs. This is how to use the ngIf directive. It can be used in all types of use cases and comparisons you can think of in your component template.
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.
The * syntax means that ngIf is a structural directive, meaning that it affects the structure of the page.
Forethought
On retrospect, this is a very interesting question. The actual question is <div *ngIf="condition; else elseBlock">
works as expected. But also does <div *ngIf="condition else elseBlock">
, so what gives? What actually is the need for the semi-colon?
Explanation
It turns out the Angular microsyntax specification that defines how *ngIf
is expanded to [ngIf]
is quite flexible and difficult to grasp initially. The official Angular docs doesn't go in-depth. A good explanation could be found here and here. Gist of the explanation is that the microsyntax definition is of the form
*:prefix="( :let | :expression ) (';' | ',')? ( :let | :as | :keyExp )*"
:prefix
: HTML attribute key.:key
: HTML attribute key.:local
: local variable name used in the template.:export
: value exported by the directive under a given name.:experession
: standard angular expression:keyExp = :key ":"? :expression ("as" :local)? ";"?
:let = "let" :local "=" :export ";"?
:as = :export "as" :local ";"?
It appears the semi-colon is optional. Additionally in our case, the else
block is a key expression and it could be seen that the colon is optional which we aren't using at the moment. So theoretically we could also use <div *ngIf="condition else: elseBlock">
. As such, the ngFor
can also be used without any semi-colon. So the following block will also work
<div *ngFor="let n of arr let i=index let f=first let l=last">
{{ n }}
</div>
Working example: Stackblitz
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