Search⌘ K
AI Features

Iterating Through Data

Explore how to iterate through data in Angular applications using the ngFor directive to render lists dynamically. Understand how to optimize rendering performance with trackBy and how to use ngSwitch to conditionally display templates. This lesson equips you to handle dynamic collections and improve app scalability with Angular structural directives.

The ngFor directive allows us to loop through a collection of items and render a template for each one, where we can define convenient placeholders to interpolate item data. Each rendered template is scoped to the outer context, where the loop directive is placed so that we can access other bindings. We can think of ngFor as the for loop for HTML templates.

The product list component we already use displays a list of products using static data on the HTML template. In a real-world scenario, data is dynamic and comes from different sources, such as a back-end server or the local storage of the browser.

How we can use the ngFor directive

We can use the ngFor directive to display the product list in a more scalable way:

  1. Open the product-list.component.ts file and create a products array in the ProductListComponent class:

products = ['Webcam', 'Microphone', 'Wireless keyboard'];
Creating the products array
  1. Modify the unordered list element in the product-list.component.html file so that it displays a <li> ...