In this post I would like to show you some nice features coming with Angular 2.

Iteration over collection using NgFor directive

Let's say that we have a list of string values (a list of system roles in our case) and we would like to display it on the screen.


In order to display all the roles wrapped with a specific HTML element, we can use syntax similar structure to Angular 1:

<p>List of roles: <span *ngFor="#role of roles">{{role}}, </span></p>

And would look like this:

Angular2 ngFor with HTML element

But what if I want to have a list or roles just as text without that extra HTML tag around each role? It can be easily done using Angular 2 <template /> syntax:

<p>List of roles: <template ngFor #role [ngForOf]="roles">{{role}}, </template></p>

And you can see that the rendered HTML has only text:

Angular2 ngFor without HTML element

So far so good. But there is one problem, which I do not like: the trailing comma character. I would like to have separating commas between roles, but not after the last role.

NgFor provides several values that can be aliased to local variables. One of them is last which is set to a boolean value indicating whether the item is the last one in the iteration.

So let's update the template and use last variable:

<p>List of roles: 
  <template ngFor #role [ngForOf]="roles" #last="last">{{role}}{{last ? '' : ', '}}</template>

And as you can see, commas are presented as expected:

Angular2 ngFor without trailing comma element

Alternatively, you can perform formatting inside your component and display already formatted string in a page.

In order to do that, you would need to create a component method returning string. Easiest and cleanest appraoch would be to use the join() method that joins all elements of an array into a string. e.g.

rolesAsString() {
    return this.roles.join(', ');

And display it in a page using Angular interpolation syntax:

<p>List of roles: {{rolesAsString()}}</p>

And that would give you following results:

Angular2 array list with interpolation syntax

See also