使用Angular提供的OnPush变更检测策略优化性能。具体实现方法如下:
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {}
import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { DatatableComponent } from '@swimlane/ngx-datatable';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent implements OnInit {
@ViewChild(DatatableComponent) table: DatatableComponent;
rows = [];
constructor(private cdr: ChangeDetectorRef) {}
ngOnInit() {
// some code to populate rows
// ...
// detach and reattach table to manually update view
this.table.rowTracking = (index, row) => row.id;
this.table.detach();
this.rows = newRows; // update rows
this.table.reattach();
this.cdr.detectChanges(); // run change detection for the entire component
}
}