تنبيه

الرجاء تحديد نص من المقال أولاً.

محتوى محمي

لتحميل هذا المقال، يرجى تفعيل جرس الإشعارات أو اختيار طريقة اشتراك أخرى.

Ahmed Bouchefra

الرئيسية
Ahmed Bouchefra

أحمد بوشفرة

Software Engineer & Tech Author

ابدأ هنا
ابدأ هنا
المكتبة
المكتبة
أكاديمية بايثون
أكاديمية بايثون
تطبيق اختبارات البرمجة
تطبيق اختبارات البرمجة
دورات يوديمي
دورات يوديمي
المسارات
المسارات
الملخصات
الملخصات
الأدوات
الأدوات
اشترك
اشترك
كتب فريق 10xdevblog
كتب فريق 10xdevblog
الكاتب: أحمد بوشفرة

Angular 10 ngFor with Index and trackBy Example

اضغط على زر PDF لتحميل المقال كملف للقراءة لاحقاً

ملاحظة: هذا المقال بقلم أحمد بوشفرة. الآراء الواردة تعبر عن الكاتب.

أحمد بوشفرة: مبرمج ومؤلف تقني، أساعد المطورين على بناء تطبيقات ويب حديثة وسريعة.

يمكنك التواصل مع الكاتب لطلب خدمات برمجية عبر:

يمكنك أيضاً نشر مقالك هنا والترويج لخدماتك أمام جمهور من المبرمجين. تواصل معنا

لخص هذا المقال باستخدام ChatGPT

انسخ الأمر أدناه والصقه في ChatGPT للحصول على ملخص سريع للمقال:

لخص لي هذا المقال في نقاط رئيسية: https://www.ahmedbouchefra.com/angular-ngfor-index-trackby-example/ تم النسخ!
فتح ChatGPT

In this post, we’ll see by examples how to use the ngFor directive to iterate over arrays of data and even objects in Angular 10 templates.

What is ngFor in Angular Template Syntax?

Angular makes use of HTML for templates associated with components which eventually represent the views of your front-end application.

A component controls a part of your application user interface and the associated template is what gets rendered in that part of the UI.

Since HTML doesn’t have a built-in template language, Angular extends HTML with a powerful template syntax that includes many directives such as ngFor which is similar to the typical for-loops in programming languages.

The ngFor allows you to loop through an array of data directly in the HTML template. The array must be present in the associated component.

How to Use ngFor in Angular 10 Templates?

Let’s now see how to use the ngFor directive by example.

Let’s suppose. we have a movies component and we want to display the movies from an array in the template. Here is how:

import { Component } from '@angular/core';

@Component({
  selector: 'app-movies-list',
  template: `
    <ul>
      <li *ngFor="let movie of moviesArr">
        
      </li>
    </ul>
    `
})

export class MoviesListComponent  {
    moviesArr: any[] = [
    {
      "title": "Super Man"
    },
    {
      "title": "Spider Man"
    },
    {
      "title": "Aladdin"
    }, 
    {
      "title": "Downton Abbey"
    }
  ];
}

The moviesArr array is automatically available in the component’s template which is in our case an inline template.

We use the ngFor directive to iterate over the array of movies and display the title of each movie.

The directive has the *ngFor="let movie of moviesArr" syntax. After the let keyword, we add a variable, which can be any valid variable name, that will be used to reference and access each element of the array and after the of keyword, we add the array of data which must be present in the component.

We also need to prefix ngFor with a * before providing the iteration expression.

The Index of ngFor Elements

Suppose that we need to display the index of each element of the movies array.

Angular provides the reserved index keyword inside the ngFor expression which can be used as follows:

import { Component } from '@angular/core';

@Component({
  selector: 'app-movies-list',
  template: `
    <ul>
      <li *ngFor="let movie of moviesArr; let i = index">
          - 
      </li>
    </ul>
    `
})

export class MoviesListComponent  { /* ... */ }

Inside the ngFor expression, we defined another variable called i which gets assigned the index keyword which simply contains the current index of each element in each iteration. And we used interpolation to display the value of the i and movie.title variables.

Note: The index starts from 0 not 1.

Angular also provides the reserved first and last keywords for getting the first and last items in the array.

The ngFor trackBy

Angular provides the trackBy feature which allows you to track elements when they are added or removed from the array for performance reasons.

we simmpl need to define a trackBy method, which needs to identify each element uniquely, in the associated component and assign it to the ngFor directive as follows:

import { Component } from '@angular/core';

@Component({
  selector: 'app-movies-list',
  template: `
    <ul>
      <li *ngFor="let movie of moviesArr; trackBy: trackByMethod">
        
      </li>
    </ul>
    `
})

export class MoviesListComponent  {
    moviesArr: any[] = [
    {
      "id": 1,
      "title": "Super Man"
    },
    {
      "id": 2,
      "title": "Spider Man"
    },
    {
      "id": 3,
      "title": "Aladdin"
    }, 
    {
      "id": 4,
      "title": "Downton Abbey"
    }
  ];
   
   trackByMethod(index:number, el:any): number {
    return el.id;
  }
}

We can simply identify each element in a unique way using its id.

Conclusion

We can use the ngFor directive to iterate over arrays of data right in the Angular’s component template.

We can use other features like index, first, last and trackBy to get the index of the current element, the first and last elements and for tracking the addition or removal of the array elements for performane reasons.

هل لديك سؤال أو استفسار؟ اترك تعليقاً بالأسفل:

احصل على المحتوى الجديد فور نشره ⚡

اختر الطريقة الأنسب لك لمتابعتنا والحصول على التحديثات مجاناً.
(اضغط على رابط التفعيل الذي سيصلك لفتح المحتوى)

عرض كل بدائل الاشتراك

احصل على موارد مجانية! 📚

اشترك في القائمة البريدية واحصل على كتب ومصادر تعليمية مجانية

تنبيه هام:

للاشتراك بنجاح، يرجى فتح الصفحة في متصفح خارجي (مثل Chrome أو Safari) وليس متصفح التطبيق المدمج.

📚 المكتبة المجانية

حمّل كتب وأدلة PDF مجانية في البرمجة وتطوير الويب

تصفح المكتبة

شارك المقال

Angular 10 ngFor with Index and trackBy Example
0:00 / 0:00