在组件的元数据中设置changeDetection属性为OnPush,并使用ChangeDetectorRef手动激活变更检测。使用不可变对象来操作数组,例如使用spread运算符或Object.assign方法来创建新数组而不是修改原有数组。
示例代码:
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
items: any[];
constructor(private cdRef: ChangeDetectorRef) {
this.items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
}
addItem() {
const newItem = { id: 3, name: 'Item 3' };
this.items = [...this.items, newItem]; // 使用spread运算符创建新数组
this.cdRef.detectChanges(); // 手动激活变更检测
}
removeItem(itemId: number) {
this.items = this.items.filter(item => item.id !== itemId);
this.cdRef.detectChanges();
}
}