@for vs *ngFor — Angular 17 : The newest version of Angular

Alif Razan Saputra
3 min readJan 13, 2024

--

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,

  1. List Chat
  2. Row Table
  3. List Photo of Instagram
  4. 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:

  1. 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;

example.component.ts

Next, lets code the for loops block syntax in HTML, like this;

example.component.html

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;

example.component.ts

Next, let’s change the HTML code, like this;

example.component.html

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;

example.component.html

Finally run and compile your Angular, then you will get this result;

Credits

  1. Image Tokyo : https://media.cntraveler.com/
  2. Image Osaka : https://photos.smugmug.com/
  3. Image Kyoto : https://static.independent.co.uk/

--

--

Alif Razan Saputra

I'd be happy to discuss programming, including topics such as Angular, NestJS, ReactJS, and more. Lastly, let's connect www.linkedin.com/in/alifrazansaputra