How to Write an Angular For Loop Without a ForEach: Complete Guide to Numeric Ranges in Templates

You cannot write a traditional for (let i = 0; i < n; i++) loop directly in Angular templates, but you can emulate one using *ngFor with a generated numeric array or a custom range function in your component class.

Angular templates do not support imperative looping constructs. Instead, the framework provides the *ngFor structural directive, which is syntactic sugar for the NgForOf directive implemented in packages/common/src/directives/ng_for_of.ts. By preparing your data as an iterable in the component layer, you can achieve traditional angular for loop behavior while maintaining the declarative nature of Angular templates.

How Angular's Looping Mechanism Works

The *ngFor directive you write in templates is compiled into an <ng-template> element that instantiates the NgForOf class. According to the Angular source code in packages/common/src/directives/ng_for_of.ts, this directive implements DoCheck and receives the iterable via its ngForOf input.

The directive creates an embedded view for each item using NgForOfContext, which exposes:

  • $implicit: The current item value
  • index: The current index (0-based)
  • first, last, even, odd: Boolean flags for position state

When you write *ngFor="let item of items; let i = index", the compiler expands this into the long-form template syntax that binds [ngForOf] to your iterable and provides the context variables.

Methods to Create an Angular For Loop

Since templates cannot execute arbitrary JavaScript loops, you must generate the sequence in your component logic and let *ngFor iterate over the resulting array.

Generate a Numeric Array with Array.from

For simple ranges (e.g., 0 to 9), create the array in your component using Array.from:

// app.component.ts
export class AppComponent {
  // Creates [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  numbers = Array.from({length: 10}, (_, i) => i);
}
<!-- app.component.html -->
<ul>
  <li *ngFor="let n of numbers">Item {{ n }}</li>
</ul>

This approach builds the array once during component initialization, keeping the template declarative.

Create a Custom Range Function

For dynamic ranges with custom start, end, or step values, implement a helper method in your component:

// app.component.ts
export class AppComponent {
  range(start: number, end: number, step = 1): number[] {
    const result = [];
    for (let i = start; i < end; i += step) {
      result.push(i);
    }
    return result;
  }
  
  // Usage: generates [5, 8, 11, 14, 17]
  numbers = this.range(5, 20, 3);
}
<!-- app.component.html -->
<div *ngFor="let n of numbers">Value: {{ n }}</div>

This method allows you to emulate any traditional for loop signature (for (i = start; i < end; i += step)) while adhering to Angular's unidirectional data flow.

Accessing Index and Context Variables

When iterating over existing data, you can still access the loop index and state flags without creating a numeric array:

<table>
  <tr *ngFor="let hero of heroes; 
               let i = index; 
               let first = first; 
               let last = last; 
               trackBy: trackById">
    <td>{{ i + 1 }}.</td>
    <td>{{ hero.name }}</td>
    <td *ngIf="first">🏅 First</td>
    <td *ngIf="last">🏁 Last</td>
  </tr>
</table>
// component.ts
trackById(index: number, hero: {id: number}): number {
  return hero.id;
}

The index, first, and last variables are provided by the NgForOfContext class defined in the Angular source code.

Optimizing Performance with trackBy

When emulating for loops over large datasets, always provide a trackBy function to minimize DOM manipulation. The NgForOf directive accepts an ngForTrackBy input that receives a function returning a unique identifier for each item.

Without trackBy, Angular destroys and recreates all DOM elements when the reference to the iterable changes. With trackBy, Angular only updates the elements that have actually changed, reusing existing DOM nodes and significantly improving rendering performance for large lists.

Key Source Files in the Angular Repository

Understanding the internal implementation helps debug complex looping scenarios:

File Purpose
packages/common/src/directives/ng_for_of.ts Contains the NgForOf directive class and NgForOfContext interface that powers *ngFor.
packages/common/src/directives/ng_if.ts Companion structural directive often used alongside *ngFor for conditional rendering.
packages/common/src/pipes/async_pipe.ts Implements the async pipe, allowing *ngFor to iterate over Observable or Promise streams.
docs/content/guide/directives/structural-directives.md Official documentation explaining how structural directives like *ngFor are expanded and executed.

Summary

  • Angular templates do not support imperative for loops; you must use the *ngFor structural directive.
  • To emulate a traditional numeric for loop, generate an array in your component using Array.from() or a custom range() function.
  • Access loop metadata (index, first/last flags) through the local variables provided by NgForOfContext.
  • Always implement a trackBy function when iterating over large lists to optimize DOM reuse and rendering performance.
  • The underlying implementation resides in packages/common/src/directives/ng_for_of.ts, which defines the NgForOf directive and its context interface.

Frequently Asked Questions

Can I use a traditional for loop inside an Angular template?

No. Angular templates only support declarative structural directives. You cannot write imperative JavaScript like for (let i = 0; i < 10; i++) directly in the HTML. Instead, prepare the numeric range as an array in your component class and iterate over it using *ngFor.

How do I get the current index in an Angular for loop?

Use the let i = index syntax within your *ngFor expression. For example: *ngFor="let item of items; let i = index". The index variable is provided by the NgForOfContext class and represents the 0-based position of the current item in the iterable.

What is the difference between *ngFor and NgForOf?

*ngFor is the shorthand microsyntax used in templates, while NgForOf is the actual directive class defined in packages/common/src/directives/ng_for_of.ts. When Angular compiles your template, it expands *ngFor="let item of items" into an <ng-template> element that instantiates the NgForOf directive with the [ngForOf] input binding.

How can I optimize large lists when using *ngFor?

Provide a trackBy function that returns a unique identifier for each item. For example: *ngFor="let item of items; trackBy: trackById". In your component, define trackById(index: number, item: any): any { return item.id; }. This tells Angular to reuse existing DOM nodes when the data changes rather than destroying and recreating them, significantly improving performance for large datasets.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →