Angular Control Flow
The past week I cursed Angular a little bit because I just wanted to have a simple if-else condition within my HTML template. But, as you probably already...
The past week I cursed Angular a little bit because I just wanted to have a simple if-else condition within my HTML template.
But, as you probably already know, we have to jump through a couple of hoops to get this working.
The result is a not-so-easy-to-read template that's prone to errors.
Angular 17 changes that by providing a new (opt-in) way on how we write our templates.
Instead of using the structural directives NgIf, NgFor, and NgSwitch, you'll be able to use the new @ syntax.
This change drastically improves the Developer's Experience;
- it's easier to read
- you don't have to import the directives
- it's less verbose since you don't have to create wrapper components e.g.
ng-container.
As an example, let's take a look at my if-else condition and compare both solutions.
@if(){<div></div>}@<div></div>@<div></div>
<ng-container*ngIf=><div></div></ng-container><ng-template#elseIfTemplate><ng-container*ngIf=><div></div></ng-container></ng-template><ng-template#elseTemplate><div></div></ng-template>
For completeness let's also take a look at the new syntaxes to iterate over a collection (*ngFor) and how to create a switch expression (*ngSwitch).
@for(oftodos;.){<li></li>}@<li></li>
@switch(.){@(''){<app-summary-card[card]=/>}@(''){<app-image-card[card]=/>}@{<app-simple-card[card]=/>}}
To already try out the new Control Flow feature before it's officialy released, update the angular compiler options within the TypeScript configuration file.
Add the _enabledBlockTypes property, and add the blocks you want to use within your application.
tsconfig.json{"angularCompilerOptions":{"_enabledBlockTypes":[,,,]}}
For more information see the Angular blog post Meet Angular’s New Control Flow.
Feel free to update this developer bit on GitHub, thanks in advance!