Iterating Through Data
Learn how to loop through a collection of items and render a template for each one.
We'll cover the following...
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:
Open the
product-list.component.tsfile and create aproductsarray in theProductListComponentclass:
products = ['Webcam', 'Microphone', 'Wireless keyboard'];
Modify the unordered list element in the
product-list.component.htmlfile so that it displays a<li>element for each item from theproductsarray:
<ul><li *ngFor="let product of products" (click)="selectedProduct = product">{{product}}</li></ul>
In the preceding code, on lines 2–4 we use the *ngFor directive and turn each item fetched ...