DEV Community

Anubhab Mukherjee
Anubhab Mukherjee

Posted on

Understanding Built In Angular Directives - Part 5

Today we will cover another important structural directive provided by the Angular Team - ngFor

The ngFor directive is used to loop through an array of items in the template. The element where the directive is written becomes the parent which is repeated.

Lets see that in practice-
We need to update our structural-directive-demo.component.ts file and add the below code -

itemsToBuy = ['Pencil', 'Notebook', 'School bag', 'Eraser'];
Enter fullscreen mode Exit fullscreen mode

and in component template file add the below code -

<div *ngFor="let item of itemsToBuy">
  {{ item }}
Enter fullscreen mode Exit fullscreen mode

Now if you start the application and open localhost:4200 in the browser you would see the below output -
Image description
Now lets understand the below code
*ngFor="let item of itemsToBuy"
Here ngFor is a structural directive so the * is appended at the start followed by the equals = operator.
Here itemsToBuy is the array we declared in the component TS file. We use the for-of syntax to loop through the array. Every item in the array is assigned to the variable item which is then printed in between div tag by using the {{item}}. The loop is auto incremented and moves to the next item until all the items are printed.
In the above example item variable holds a string value.
Similarly the array can also be a list of objects.
In that case at every iteration item would hold an object.

A word of Caution
You should not use two structural directives on the same element.

For example ngIf and ngFor at the same div element is not allowed.

That's all about ngFor. Hope you enjoyed the post.
Please like, comment and share
The last structural directive is on your way. So stay tuned.

Happy Coding

Top comments (0)