How to Use the ngFor Angular Directive

Angular uses directives to dynamically render certain HTML elements on your website. One of the structural directives you can use is ngFor.

The ngFor directive allows you to repeat the same block a specified number of times, or loop through an array of objects to display their details. It’s a powerful tool that you can even use to render objects within other objects.

4

It also has many functions that can be useful in specific scenarios. This includes finding the first and last elements or skipping certain items.

How to Use ngFor to Loop Through Static Numbers

The ngFor directive is based on the for loop, one ofmany useful loops that JavaScript supports. As of the current version of Angular (14), you will need to create an array that has the number of items you want to loop through.

How to Skip or Style Certain Numbers

You can use theoddorevenngFor variables to determine every second number. A scenario where you might find this useful is if you want to style every odd or even row in a table using a different color.

How to Count Backward

To count backward, you can use traditional methods such as reversing a list or counting backward through the loop using an index.

How to Style the First and Last Element Differently

you may style the first and last elements separately from the other elements using thefirstandlastAngular variables. This is an alternative tousing CSS psuedo-classeslike:first-child.

How to Use an ngFor to Iterate Over Objects

You can use the ngFor directive to loop through objects and access their individual variables.

How to Use a Nested ngFor to Display Objects Inside Other Objects

You can use a nested for loop to display objects inside other objects.

Looping Using ngFor in Angular

You can use the ngFor structural directive to dynamically loop through HTML elements on your website. This will allow you to repeat the same block for a number of objects, or for a specified number of times.

You can also use it to do other tricks such as skipping every even or odd number or styling the first and last element. You can also use it to dynamically render many objects within other objects.

Dell monitor showing Windows 10 desktop

There are other Angular directives that you can use to help make your website more dynamic. These include ngIf, ngSwitch, ngStyle, ngClass, and ngModel.

Angular’s directives add additional behavior to parts of your application. Find out how to use the most common and useful directives.

MacBook and a Dell laptop running ZorinOS next to each other

When your rival has to bail out your assistant.

I found my TV was always listening—so I shut it down.

firefox logo with yellow warning symbol

Every squeak is your PC’s way of crying for help.

This small feature makes a massive difference.

View from behind somebody sitting at a computer, with the screen in full view, displaying source code.

Tor spoiled me forever.

Technology Explained

PC & Mobile