In Angular, ngFor
is a structural directive used to iterate over a collection of items and create a template for each item. Here’s how to use ngFor
:
- Start by importing the
CommonModule
in your module.
import { CommonModule } from '@angular/common';
- In your component, create an array of items that you want to iterate over.
items = ['item1', 'item2', 'item3'];
- In your template, use
ngFor
to iterate over the array of items.
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
In the example above, we’re creating an unordered list and using ngFor
to create a list item for each item in the items
array. The *
ngFor
directive is applied to the <li>
element, and we’re using the let
keyword to define a template variable item
to represent the current item in the iteration. Finally, we’re using the double curly braces {{ }}
to display the value of the data
variable.
You can also use ngFor
with other types of data structures such as arrays of objects. For example:
items = [
{ name: 'item1', price: 10 },
{ name: 'item2', price: 20 },
{ name: 'item3', price: 30 }
];
<ul>
<li *ngFor="let item of items">
{{ item.name }} - {{ item.price }}
</li>
</ul>
In the example above, we’re using ngFor
to iterate over an array of objects. We can access each property of the object using dot notation (item.name
and item.price
).