如何提高渲染性能?

How to improve performance of rendering?

我有将每次响应数据添加到数组的服务:group: [].

其中响应是对象:

{"items": [{"id": 1}, {"id": 2}, {"id": 3}]}

问题是它在模板中渲染的时间太长,每次数组发生变化时都会渲染group:

<div class="SearchResultGroup" *ngFor="let layer of group">
   <div class="SearchResultGroup" *ngFor="let l of layer.items"></div>
</div>

如何提高渲染性能?

您可以通过在组件中使用 ChangeDetectionStrategy.OnPush 来控制何时进行更改检测。

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent  {
  constructor(private changeDetector: ChangeDetectorRef) { }

  someMethod(): void {
    // do lots of heavy stuff

    // now trigger change detection

    this.changeDetector.detectChanges();
  }
}

changeDetection: ChangeDetectionStrategy.OnPush 添加到装饰器表示您将告诉 Angular 何时 运行 更改检测。

this.changeDetector.detectChanges() 告诉 Angular 您现在已准备好进行 运行 更改检测。

此策略意味着您可以静默更新模型并一次性触发变更检测。