Angular Built-in Directives: ngFor

In the previous tutorial in this directives series, we discussed how to create and use directives. Now, we will discuss ngFor.

Ngfor is a built-in directive that stands as a standard for loop. Basically, it iterates in each element in a given collection or list. Let’s look at it in code:

This is a sample *ngFor directive with a given string collection named ‘stock’

Now let’s make our sample list of stock markets using Angular ngFor directive. First thing we need to do is create the data collection we need for our list. Go to your previously created stocks.component.ts file and create a stockMarket array. In export class write:

Next, we will now create the loop inside the Component decorator.

The loop is written inside the template because it acts as the view of our component.

To see your work, save it and go back to your browser (provided that you’re still running the command ng serve from the integrated terminal).

ngfor

And that is how you use the ngFor built-in directive. On the next article, we will cover another type of built-in directive: ngIf.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.