ngFor in Angular
2 min readApr 22, 2024
ngFor
is a built-in Angular directive that streamlines iterating over collections (arrays) in your templates. It's similar to JavaScript's for
loop, but specifically designed for the world of Angular.
Code Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent {
products = [
{ name: 'Apple', price: 1.99 },
{ name: 'Banana', price: 0.79 },
{ name: 'Orange', price: 2.49 }
];
}
- Inside the component class, we define an array named
products
containing objects with product details (name and price).
<ul>
<li *ngFor="let product of products">
{{ product.name }} - ${{ product.price }}
</li>
</ul>
- Inside the list, we use
*ngFor
on each<li>
element. let product
: This creates a variable namedproduct
that holds the current product object during each iteration.of products
: This specifies the array to iterate over, which is theproducts
array in this case.- Within the
<li>
, we display product information using interpolation ({{ }}
).
Explanation:
- Angular encounters
*ngFor
. - It iterates over the
products
array. - For each product object, it:
- Creates a new
<li>
element. - Assigns the current product to the
product
variable. - Renders the product name and price inside the list item.
Additional Notes:
ngFor
works with arrays of any data type, not just objects.- You can access object properties within the loop using dot notation (e.g.,
product.name
). - For more complex scenarios, you can use
index
to get the current item's position (*ngFor="let product of products; let i = index"
).
By using ngFor
, you efficiently display dynamic content based on collections in your Angular applications.