ngFor with Angular 2 and TypeScript - Loading..
Style: Blog or IDE

ngFor with Angular 2 and TypeScript

ngFor is a repeater directive which outputs a list of elements by iterating over an array.

Updated Jan 2017, Angular version 2.4.x

Quick Tip

In the text below, when you see a word or phrase with this color, click on it to highlight the source code.

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style


In the code snippet below we use the ngFor directive to iterate over the people array and store each item in a template variable called person. This variable is then accessed within the template using interpolation. We highlight every other row by applying a CSS class when the row is odd. Angular provides an even value too.

In the second ngFor statement we use a function to generate an array to loop over. index provides a zero-based incrementing value for each item in the array. last identifies the last item in the array allowing us to omit the final comma. Angular also provides the first value as you would expect.

ng-for.component.ts x

The Application

Here is the output from this component.


Where Next?

More Directives

To learn more about the other built-in directives, take a look at these tutorials.

  • ngIf adds and removes elements in the DOM based on the results of an expression.
  • ngSwitch displays one element (and its children) from a set of possible options, based on some condition.
  • ngClass adds and removes CSS classes on an element.
  • ngStyle sets CSS styles on an HTML element conditionally.