The new Angular template syntax
posted in javascript on • by Wouter Van Schandevijl •Compared to other SPA frameworks, Angular really made it quite cumbersome to do simple things like an if/else to show/hide certain UI parts.
The new syntax is so much more succint, it gets rid of excess
html tags, is easier to remember and it doesn’t need to be
added to the imports
array of a standalone component.
@if
Old Syntax
Need to import NgIf
from @angular/common
.
<div *ngIf="boolVar; else boolFalse">
TRUE
</div>
<ng-template #boolFalse>
FALSE
</ng-template>
New Syntax
@if(boolVar) {
TRUE
} @else {
FALSE
}
@for
Old Syntax
Need to import NgFor
from @angular/common
.
<span *ngFor="let el of elements; index as i; first as isFirst">
{{ i }}: {{ el }} (first={{isFirst}})
</span>
Available “special” variables:
- index & count
- odd & even
- first & last
Adding trackBy: trackElFn
is optional
and is only needed when you are running into performace issues.
trackElFn(index: number, el: T) {
return el.id;
}
New Syntax
The track is mandatory in the new syntax.
@for(el of elements; track element; let index = $index; let first = $first) {
{{ index }}: {{ el }}
}
@switch
Old Syntax
Need to import NgSwitch
, NgSwitchCase
and NgSwitchDefault
from @angular/common
.
<div [ngSwitch]="aNumber">
<span *ngSwitchCase="1">ONE</span>
<span *ngSwitchCase="2">TWO</span>
<span *ngSwitchDefault>OTHER</span>
</div>
New Syntax
@switch(randomNumber) {
@case(1) {ONE}
@case(2) {TWO}
@default {OTHER}
}
@let
Old Syntax
This was previously not possible out of the box but the
same could be achieved with an ngIf
:
<div *ngIf="randomObs$ | async as randomNr">
Nr = {{ randomNr }}
</div>
New Syntax
Don’t forget the ending ;
!
@let randomNr = randomObs$ | async;