1

I render array of object in template using ngFor:

<tr *ngFor="let p of rows; let i = index">
        <td class="tableDefault__td tableDefault__center td__number">
          {{ i + 1 }}
        </td>
        <td class="tableDefault__td tableDefault__center td__date">
          <div class="history_item" *ngFor="let h of p.history">
            <span class="span_link" (click)="goto(h)"
              >{{ h.classNumber }}{{ h.classSuffix }},
              {{ formatDate(h.whenDate) }}</span
            >
          </div>
        </td>
        <td class="tableDefault__td tableDefault__center td__theme">
          <input
            [disabled]="!isOwner(teacherId)"
            type="text"
            name="subject"
            placeholder="{{ 'create_plan_e_name' | translate }}"
            [(ngModel)]="p.topic"
            autofocus
          />
        </td>
</tr>

Rendering works so slowly when array rows container more then 400 objects. How to optimize rendering or cache it? Perhaps problem is in nested loop *ngFor="let h of p.history"?

1 Answer 1

3

You can use a trackBy function in you ngFor directive to improve performance by providing an unique id. It allows Angular to better handle the change detection concerning the array you bound.

Something like:

HTML

<tr *ngFor="let p of rows; trackBy: trackByFunction; let i = index">
    ....
</tr>

TS

public trackByFunction(index, item) {
    if (item) {
        return item.id;
    }
    return null;
}

Here is a good example.

And the official documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Track by accepts custom function, what function should return? Why do you return item.id instead item?
It must return an unique identifier so that Angular can only reload specific elements in you array and not the whole array when a change is detected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.