Debug School

rakesh kumar
rakesh kumar

Posted on

Difference between ng-repeat and ng-for

In AngularJS, ng-repeat and ng-for are both directives used to iterate over a collection of items and display them in the view. However, ng-repeat is specific to AngularJS, while ng-for is specific to Angular (version 2 and later). Here's a breakdown of the differences between the two:

ng-repeat:

Used in AngularJS.
Syntax:

ng-repeat="item in collection"
Enter fullscreen mode Exit fullscreen mode
  1. Iterates over each item in the collection and creates a new DOM element for each item.
  2. Can be used with any iterable object in JavaScript, including arrays, objects, and strings.
  3. Supports a range of special properties, including $index (the current iteration index), $first (whether the current item is the first in the iteration), and $last (whether the current item is the last in the iteration) . Here's an example of using ng-repeat in AngularJS to display a list of names:

Image description

ng-for:

Syntax:

*ngFor="let item of collection"
Enter fullscreen mode Exit fullscreen mode
  1. Iterates over each item in the collection and creates a new DOM element for each item.
  2. Can only be used with arrays and other iterable objects that implement the Iterable interface in TypeScript.
  3. Supports a range of special properties, including index (the current iteration index), first (whether the current item is the first in the iteration), and last (whether the current item is the last in the iteration) .

Image description

Note that the syntax and special properties are slightly different between ng-repeat and ng-for, so it's important to use the correct directive for your version of Angular.

Top comments (0)