*ngFor directive in Angular

In Angular, the *ngFor directive is a powerful tool for rendering a template for each item in a collection.

  1. Purpose of *ngFor:

    • The *ngFor directive is used to repeat a portion of an HTML template for every item in an iterable list (collection).
    • It’s similar to the ngRepeat directive in AngularJS.
  2. Basic Syntax:

    • The shorthand form of *ngFor is commonly used:
      HTML
      <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
    • This shorthand expands into a longer form using the ngForOf selector within an <ng-template> element:
      HTML
      <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
        <li>...</li>
      </ng-template>
  3. Exported Variables:

    • *ngFor exports 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.
  4. Example Usage: Suppose you have an array of users:

    TypeScript
    users = [
      { name: 'Alice' },
      { name: 'Bob' },
      { name: 'Charlie' }
    ];

    You can use *ngFor to 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:

      1. Alice (default)
      2. Bob
      3. 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
*ngFor directive in Angular


Post a Comment

0 Comments