Angular 7/8 | NgFor and TrackBy quick tutorial by example

In Angular DOM if we want to Iterate over each item in a collection (Which can be an Array or Object), then we use NgForOf Directive.

In this tutorial, we will discuss *ngFor structure directive with a quick example and get to know how we can use NgFor in different real-world application scenarios.

Structural directives are used to make changes in HTML layout by adding, removing, repeating or manipulating elements in DOM structure.

How to use *ngFor Directive?

NgFor directive is added to element as an attribute property which takes a collection which can be an Array of Items or an Object.

Simple Array as Collection

JSON Object as Collection

In the above example, we added *ngFor=”let fruit of fruits” with of operator to fetch each item in the collection fruit and loop over all items to create a clone of the element with different item values.

How to get Index of Each Item in ngFor Directive in Angular?

In some situations, we may need to get Index of the current item in the collection. Suppose we want to show S.no of items.

We use Index keyword as shown below:

*ngFor=”let fruit of fruits; let i = index

Here 1 is added above {{ i + 1 }} as index starts from 0.

Use First, Last, Even & Odd Keywords

There are available keywords which returns boolean values true or false. Which can be used as follows:

Optimize *ngFor by using trackBy

Whenever complete collection or some of the items are updated, Angular finds no way to get to know the place of change, so it rerenders the whole list of items to update the collection on view.

It doesn’t affect much if the app is small but in case it’s more complex and handles multiple transactions on view then rerendering may cost on memory resources making view to fluctuate or respond slow.

So it’s a good practice to optimize application and Help Angular by adding a trackBy keyword in the following way:

trackByFn must return a unique identifier, which can be item index or the item id

Total items in collection using count keyword

There is also a count keyword to get total items in the collection.

 

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of