@for vs *ngFor — Angular 17 : The newest version of Angular
Hello developers, for loops are a frequently discussed topic in Angular, Not only in Angular but in many others programming languages. Why? Every time we want to display an object or data sent from the backend, it is often necessary to use for loops. For Example,
- List Chat
- Row Table
- List Photo of Instagram
- And so many others.
So today we are going to learn how to use for loops in newest version of Angular and the previous version of Angular.
Before we talk about ngFor or @for loops in Angular 17, please install some requirentments bellow:
- PrimeNG
You can read the full guidance installation in this link PrimeNG
npm install primeng
2. PrimeFlex
You can read the full guidance installation in this link PrimeFlex
npm install primeflex
Next, after all the installation is done now let’s focus to the material.
1. *ngFor
First, we have to import the ngFor from “@angular/common” and also CardModule from “primeng/card”, like this;
Next, lets code the for loops block syntax in HTML, like this;
Finally, run your Angular with npm start and you will get this result;
2. @for
First, let’s remove ngFor module from the import section of the standalone component, like this;
Next, let’s change the HTML code, like this;
In the new block syntax for loops in Angular 17, we have track and this is mandatory.
The value of the
track
expression determines a key used to associate array items with the views in the DOM.
And you can optionally include an @empty
section immediately after the @for
block content, like this;
Finally run and compile your Angular, then you will get this result;
Credits
- Image Tokyo : https://media.cntraveler.com/
- Image Osaka : https://photos.smugmug.com/
- Image Kyoto : https://static.independent.co.uk/