Why I like Angular: ng-repeat / ngFor

Continuing the theme from my previous post about two-way data binding, I’m going to cover another simple yet powerful feature of Angular: creating repeating elements.

I’m going to cover both the Angular 1 syntax and the Angular 2+ syntax as the concept is the same across both.

A lot of Angular’s power comes from making HTML more expressive, and the repeat/for loop is a very good example of that. A common use case for web apps is obtaining a list of items from the server, and then rendering them on the page. With Angular we can write the HTML for displaying a single item, and then just add an ng-repeat expression to repeat that HTML element for each item in the list.

Let’s start with a very simple bit of HTML that displays two list items:

<ul>
  <li>Apple</li>
  <li>Orange</li>
</ul>

Now let’s convert it to use Angular 1’s ng-repeat directive:

<ul>
  <li ng-repeat="fruit in ['Apple','Orange']">{{ fruit }}</li>
</ul>

This looks the same as before when rendered. The <li> element is duplicated for every item in the given list, and the fruit variable takes the value of each item in the list in turn.

The Angular 2+ syntax uses *ngFor instead, like this:

<ul>
  <li *ngFor="let fruit of ['Apple','Orange']">{{ fruit }}</li>
</ul>

This is a basic, somewhat contrived example to show the syntax. A more realistic example would obtain the list from the server, and then create an Angular component for each one. For example, if the component is called myComponent, and the list is available on the controller as ctrl.items, the HTML might look something like this:

Angular 1:
<myComponent ng-repeat="item in ctrl.items" item="item"></myComponent>
Angular 2+:
<myComponent *ngFor="let item of ctrl.items" item="item"></myComponent>

 

There are a number of additional options available for more complicated cases, such as iterating over the properties of an object, or the ability to access the index of each element in the list using the $index special property (or the exported index property in Angular 2+). But even in the simple case, it is still a powerful tool that reduces the amount of code you need to write.

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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