Angular 2 *ngFor select/option 的性能问题

Angular 2 *ngFor performance issue with select/option

我正在使用 *ngFor 来填充 <select></select>options。我的问题是我的 6 <select> 中的 1 个可以有 1000 数组值。性能正在下降。我知道这是因为 changeDetectionOne-way Binding。有没有办法更好地为 <option> 实现 *ngFor。我实际上并不需要 change detectionone-way binding.

我的代码

<select [formControl]="requestForm.controls['SellCommodityId']">
   <option [value]="" disabled selected>COMMODITY/GRADE</option>
   <option [value]="item.Id" *ngFor="let item of fieldOptions?.Product;">{{item.Value}}</option>                
</select>

2016 年 12 月 20 日更新

我将 select 放入它的一个组件中,如下所示:

import { Component, ChangeDetectionStrategy,Input } from '@angular/core';
/**
 * <ihda-select [list]="list" [control]="control" [titleOption]="title"></ihda-select>
 */
@Component({
  selector:'ihda-select',
  changeDetection:ChangeDetectionStrategy.OnPush,
  template:`
    <select [formControl]="control" class="form-control">
       <option [value]="" disabled selected>{{titleOption}}</option>
       <option [value]="item.Id" *ngFor="let item of list">{{item.Value}}</option>                
     </select>
  `,
  styleUrls: ['../app.component.css']
})
export class IHDASelect{
    @Input() list: any[];
    @Input() control: any;
    @Input() titleOption: string;
}

性能问题仍然存在。

好像不是changeDetection,因为我试过<select>中删除[formControl]属性,然后就没有表演了issue. 似乎在此处使用 [formControl] 属性为表单组跟踪它会导致性能问题。有这方面的资料吗?或者我该如何解决?

2016 年 12 月 21 日更新

此处的 plunker 中显示的性能问题:

https://plnkr.co/edit/2jNKFotBRIIytcmLto7y?p=preview

如果单击Options Route,加载选项需要很长时间。如果您删除表单代码,则路由不会花费很长时间来加载。

如果您当前组件的更改检测不是 OnPUsh ,您可以将此 select 包装在一个组件中,并将其设为 OnPush 并将产品列表传递给它以供使用。

@Component({

  selector:'my-select',
  changeDetection:ChangeDetectionStrategy.OnPush,
  inputs:['list','control'],
  template:`
    <select [formControl]="control">
       <option [value]="" disabled selected>COMMODITY/GRADE</option>
       <option [value]="item.Id" *ngFor="let item of list">{{item.Value}}</option>                
     </select>

  `
})

export class MySelectCompoent{

}

然后使用它:

   <my-select [control]='requestForm.controls['SellCommodityId']' [list]='fieldOptions?.Product'></my-select>

那么谁提供了这个列表,如果想要更新它,应该替换它。

When the Options route is selected all <options> for all <select> are rendered in one go before the application responds again.

为了避免 <options> 的呈现可能会延迟,以便它们仅按需呈现

<select [formControl]="control" class="form-control" (focus)="hasFocus = true">
   <option [value]="" disabled selected></option>
   <ng-container *ngIf="hasFocus">
     <option [value]="item.id" *ngFor="let item of list">{{item.value}}</option>                
   </ng-container>
</select>

https://plnkr.co/edit/KRgYHktFXHyPugS3nPQk?p=preview

可以进一步优化该策略,以便在组件已经一次显示一个 <select> 之后,将 hasFocus 设置为 true 由计时器延迟,这样虽然浏览器处于空闲状态,它已经呈现 <option>s.