What is the use of the 'ngFor' directive in Angular?

Understanding the Use of 'ngFor' Directive in Angular

The 'ngFor' is a built-in directive in Angular, a popular web development framework, that allows us to repeat a particular template for each item present in a list or an array. The 'ngFor' directive is often termed as a "repeater" directive because it can create copies of HTML elements and generate a dynamic list.

Consider this basic example:

<ul>
  <li *ngFor="let item of items">
    {{ item }}
  </li>
</ul>

In the above code, *ngFor directive is used with a li element. The "items" is an array and 'item' represents each element in the array 'items'. For every item in the 'items' array, the 'ngFor' directive will make a copy of the 'li' element and insert it into the DOM.

Note the use of the "let" keyword - it's used to define a local variable in the template view. In this case, 'item' is the local variable that represents the current item from the 'items' array. The expression within the double-curlies '{{ }}' is called a template expression - in this case, it's used to display the value of each 'item' in the array.

The result is a dynamic list where each item in the 'items' is displayed as a separate list item in a bullet point list.

Best Practices and Additional Insights

  • Always use the 'trackBy' option with 'ngFor' for a performance boost. 'trackBy' improves performance by reusing existing DOM elements instead of completely recreating them whenever data changes.
  • Limit the use of 'ngFor' on large collections to avoid performance drawbacks.
  • Pair 'ngFor' directive with other directives such as 'ngIf' to create more complex and dynamic templates.
  • Always ensure that the list or array used in conjunction with 'ngFor' is defined before the view is rendered to avoid any errors or empty elements in the DOM. Use Angular's lifecycle hooks such as 'ngOnInit()' to make sure any data fetching operations are completed before the view loads.
Do you find this helpful?