Semicolon in *ngIf directive with else block - Angular

Viewed 791

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?

2 Answers

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

The semicolon is only required if you are using the "else" block. So, <div *ngIf="condition"> (without the semicolon) is the canonical form when not using an 'else', but <div *ngIf="condition;"> (with the semicolon) is also valid, and <div *ngIf="condition; else elseBlock"> is the required form when using 'else'.

There are also couple of other interesting syntax options that I wasn't aware of until I looked carefully at the documentation.

Related