Angular’s For statement

Let’s say you want to add multiple components on an html page, and that in your component’s ts file you have declared an array of users, and on your html template you want to display each user.

In your ts file you have something like this:

export class UsersComponent implements OnInit{
//hard code an array of users here. Of course you'll really want to pull these from somewhere.
users = ['Smith, Jim', 'Brown, Jane', 'White, Anne'];


In your html template, we want to display the users from our ts file. We assume we have already created an ‘app-user’ component. Here’s our html file

[div] some html [/div]
[app-user *ngFor="let usr of users"][/app-user]

* ‘users’ above must match the variable in your ts file, but ‘usr’ could have been set to ‘u’, ‘user’, ‘x’, or whatever you want.

Like ngIf, ngFor is another Structural Directive, and therefore it needs the *.

Indexes in a for loop

Let’s say that you need get the index of your items. I can’t think of great reason to use an index in the sample above, … anyway, here is how you can get the index of the array items.

[div] some html [/div]
[app-user *ngFor="let usr of users; let i = index;"][/app-user]

*’index’ is a key word, but ‘i’ is just a variable I chose. The above example is contrived, but the point is you can get the index of the array item.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s