In Angular, the *ngFor directive is a powerful tool for rendering a template for each item in a collection.
Purpose of
*ngFor:- The
*ngFordirective is used to repeat a portion of an HTML template for every item in an iterable list (collection). - It’s similar to the
ngRepeatdirective in AngularJS.
- The
Basic Syntax:
- The shorthand form of
*ngForis commonly used:HTML<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> - This shorthand expands into a longer form using the
ngForOfselector within an<ng-template>element:HTML<ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> <li>...</li> </ng-template>
- The shorthand form of
Exported Variables:
*ngForexports several local variables that can be aliased for convenience:index: The current iteration index.first: A boolean indicating if it’s the first iteration.last: A boolean indicating if it’s the last iteration.odd: A boolean indicating if the index is odd.even: A boolean indicating if the index is even.
Example Usage: Suppose you have an array of users:
TypeScriptusers = [ { name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' } ];You can use
*ngForto display each user’s name:HTML<ul> <li *ngFor="let user of users; index as i; first as isFirst; last as isLast"> {{ i + 1 }}. {{ user.name }} <span *ngIf="isFirst"> (default)</span> </li> </ul>This will render:
- Alice (default)
- Bob
- Charlie
Remember that when using the shorthand syntax, Angular allows only one structural directive on an element. If you need to iterate conditionally, place the *ngIf on a container element wrapping the *ngFor element
| *ngFor directive in Angular |

0 Comments