如何提高ngFor循环的性能? [英] How to improve performance of ngFor loop?

查看:88
本文介绍了如何提高ngFor循环的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当ngFor应该呈现7600个字符串项时,性能非常慢,浏览器会在几秒钟内冻结。

When ngFor should render 7600 items which are strings, then performance are very slow, browser freeze on couple of seconds.

以某种方式可以提高ngFor的性能吗?

Is somehow possible to improve performance of ngFor?

ng代码:

  <ul *ngIf="isOpen"
    class="nano-drop-down-list"
    dropdownMenu>
    <li class="nano-f-r nano-f-30">
        <input [(ngModel)]="searchString"
               class="nano-f nano-p-0_10 nano-bc-ws hover-effect"
               placeholder="Search..." type="text"/>
    </li>

    <!-- ngFor which should be improved -->
    <li *ngFor="let option of arrayOfOptions | nanoSearchByKey:searchString:displayProperty;"
        [ngClass]="{'active':isOptionSelected(option[valueProperty])}"
        class="nano-f-r nano-f-30 nano-bc-ws hover-effect">
        <button (click)="handleClickOnOption(option[valueProperty]);"
                type="button"
                class="nano-f-c nano-f nano-p-0_10 nano-overflow-h">
            <div class="nano-f-r nano-f">
                <span class="nano-m-aaa0 nano-overflow-e">
                    {{ option[displayProperty] }}
                </span>
                <div *ngIf="isMultiple"
                     class="nano-f-r nano-f-30">
                    <i *ngIf="isOptionSelected(option[valueProperty])"
                       class="fa fa-check nano-m-a"
                       aria-hidden="true"></i>
                </div>
            </div>
        </button>
    </li>
</ul>


推荐答案

NgForOf 附带了通过函数覆盖轨道的选项(来源)。
它允许您选择应检查更改的属性/条件角度。

NgForOf in Angular 6 comes with the option to override the track by function (source). It allows you to choose what property/condition angular should check changes against.

为此,只需向组件添加一个方法,如下所示:

For that, simply add a method to your component like so:

trackByFn(index, item) {
  return item.someUniqueIdentifier;
  // or if you have no unique identifier:
  // return index;
}

在组件HTML中,您将循环更改为

Whereas in your components HTML you change the loop to

<li *ngFor="let option of arrayOfOptions | nanoSearchByKey:searchString:displayProperty; trackBy: trackByFn"
        [ngClass]="{'active':isOptionSelected(option[valueProperty])}"
        class="nano-f-r nano-f-30 nano-bc-ws hover-effect">

Angular会自动将当前索引以及当前项传递给函数。

Angular will automatically pass the current index, as well as the current item to the function.

这里一篇更好的帖子,更具体的例子和更多信息(感谢 @Pedro Arantes )。

Here's a good post with a more concrete example and further information (Thanks @Pedro Arantes).

这篇关于如何提高ngFor循环的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆