Angular ngFor - learn all features


In this post, we will learn about a built-in directive ngFor in Angular. Directives are markers on DOM elements which tells Angular to attach a specific behavior to the dom elements. Directives can even transform or sometimes hide or show the dom elements based on the type of directive. Most of the directives are prefixed with ng which means Angular. There are three types of directives in Angular which are as follows:

1. Component - directives which have templates.

2. Structural directive - These types of directives will change the layout of the DOM by adding or removing the elements from the DOM. These directives are responsible to change the structure of the layout. NgFor, NgIf are examples of the structural directive.

3. Attribute Directive - These attributes will change the appearance of elements, directives or components. Changing color, applying some class, changing the look and feel of DOM elements on specific actions, etc are done with these directives. NgClass, NgStyle are examples of an attribute directive.


What is *ngFor?

*ngFor is a structural directive in Angular. It iterates over the collection of data. Using ngFor we can display changes in the data display at runtime. The data will be updated by default in the display iterated by ngFor. Whenever there is a collection of day to display in Angular, we will generally use ngFor to show in the DOM. It is used for data representation in list and tables in HTML template. Let's take some example of the collection of data as follows:


Employee
Employee data to display
With ngFor we can print this data on our DOM using the following syntax. In this syntax, you need to take care of major things:

  • A loop variable is defined using the let keyword.
  • Don't forget to use the let keyword before making a local loop variable.
  • You will not be able to access this loop variable outside this ngFor section. Its visibility is inside this section only.
  • You will get a ngFor error as "Can't bind to 'ngFor' since it isn't a known property of 'li'." It will happen when you forget to use either let keyword or you have used in instead using 'of'.

<div>
      <ul>
            <li *ngFor="let e of employee">
              {{e.id}}{{e.name}}
            </li>
     </ul>
</div>


Why * before ngFor?

The * is generally used with structural directives. The asterisk sign is to read and write directives that modify the DOM layout using templates. When Angular sees * it will use the DOM element to render the loop one by one. *ngFor, *ngIf, *ngSwitch all are used to add or remove the elements from the template.

Finding the index of the list

We can find the index of the element using the index variable with the same "let" keyword. The index is always zero-based starts from 0,1,2,3, and so on. We can index the item we are iterating over by assigning the index to a variable in the ngFor expression. 

<div>
      <ul>
            <li *ngFor="let e of employee; let i=index;">
              {{e.id}}{{e.name}}
            </li>
     </ul>
</div>

Striping first, last, even and odd of the list

Sometimes we want to apply some class on the first element of the list, or even element of the list. This can be achieved using the syntax mentioned below. first,  last, even, odd are assigned to some variable. 

<div>
      <ul>
            <li *ngFor="let e of employee; let i=index; let first = first; let last = last; 
               let even = even; let odd = odd;"  [ngClass]="{ odd : odd, even : even,
first : first, last : last }">
              {{e.id}}{{e.name}}
            </li>
     </ul>
</div>

How ngFor handle things?

The ngFor works when we add or remove the elements from the list. It will continuously be adding or removing elements from the DOM. If the list gets modified, ngFor will work constantly to work on this operation. This is a costly operation. When we pass a new list to ngFor it will not recreate the DOM every time. It will try to use the existing DOM elements and try to overwrite only the values inside them. This decision is taken uniquely for every element in the list. 
  • How *ngFor track items?
    In the case of a large collection of data and list-items, we might face performance issues due to continuous creating and destroying of data on the screen. The UI will become very slow in this scenario. We can use trackBy to track the list-items. We can help Angular to track the items using the trackBy function. The trackBy function takes the index and the current item as a parameter and returns the unique identifier for this item.  
<div>
      <ul>
            <li *ngFor="let e of employee; trackBy: trackByFn">
              {{e.id}}{{e.name}}
            </li>
     </ul>
</div>

trackByFn(index, item) {
return index; //or item.id
}

Now when we change the item in the collection, Angular can track which
items are created or destroyed based on the unique identifier. It will create or
destroy only the items that have changed.















Comments