Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 24, 2021 07:40 pm GMT

Understanding Built In Angular Directives - Part 5

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

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'];

and in component template file add the below code -

<div *ngFor="let item of itemsToBuy">  {{ item }}</div>

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.

Cheers!!!
Happy Coding


Original Link: https://dev.to/anubhab5/understanding-built-in-angular-directives-part-5-gli

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To