Managing loops effectively in AngularJS is essential for creating dynamic and interactive applications.
In AngularJS, the ng-repeat directive is commonly used to iterate over arrays.
Controller:
$scope.items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
Template:
This example iterates over the items array and displays each item in an element.
To create a range of numbers for looping without a predefined array, use a custom filter.
Controller:
app.filter('range', function() { return function(input, total) { total = parseInt(total, 10); for (var i = 0; i < total; i++) { input.push(i); } return input; }; });
Template:
{{n}}The range filter generates an array from 0 to 99, which ng-repeat then iterates over to create 100elements.Dynamic Min/Max Ranges
To handle dynamic min and max values. This filter generates an array from min to max, which ng-repeat iterates over.
Controller: app.filter('range', function() { return function(input, min, max) { min = parseInt(min, 10); max = parseInt(max, 10); for (var i = min; i <= max; i++) { input.push(i); } return input; }; });Template:
{{n}}Angular (2+): *ngFor
In modern Angular (2+), you generate ranges in the component and use *ngFor in the template to iterate over them. This approach keeps the template clean and leverages the component’s logic for dynamic range generation, improving maintainability and readability.
Component (TypeScript): export class MyComponent { range: number[]; constructor() { const total = 100; // Or any dynamic value this.range = Array.from({ length: total }, (_, k) => k + 1); } }Template:
{{i}}Here, Array.from creates an array of numbers from 1 to total, which *ngFor iterates over.
Angular (17+): New @for Syntax
Angular 17 introduces the @for syntax, which simplifies iteration in templates, replacing the need for ngFor and improving both readability and performance.
Template:@for (let item of items; trackBy: item.id) {
- {{ item.name }}
} @empty() {- No items found
}Here, @for iterates over the items array, and the trackBy function is used to uniquely identify items and optimize rendering. This eliminates the need for *ngFor, making the template cleaner. Use @empty keyword for rendering content when the array is empty.