{ id:123, version 1, ...}
I am writing an Angular 2 component that uses the onPush change detection strategy. I'd like to know if there is a way to use custom logic with onPush when determining if an object has changed. My understanding is that onPush checks the object reference an so only updates when a new instance of an object is sent.
My app tracks its own versioning for objects which means that every object has an id and version number. I periodically refresh data from the server which means that a new object is instantiated even though the data has not actually changed. This means there are cases with the default onPush that would see a new instantiated object and think it has to update. In actuality the id and version number are the same so even though the the object reference has changed I can skip updating the component.
I'd like to be able to provide a custom function to onPush that essentially uses a function like this to do change checking.
(obj1, obj2) => obj1.id === obj2.id && obj1.version === obj2.version
Is it possible to customize the onPush logic, or is there another way to achieve this so that I don't need to unnecessarily update the component when the object reference changes but the data does not.
I don't think that it's possible to create a custom changeDetectionStrategy
. But if you do track the change on your objects by yourself you can do something (probably) even more optimized.
You can inject the ChangeDetectorRef
and tell Angular that your component shouldn't be watched anymore (which is pretty cool and powerful !).
constructor(private _cd: ChangeDetectorRef)
ngOnInit() {
this._cd.detach();
}
ngOnChanges() {
// check if your objects have changed here
// if they've changed, tells Angular to check
// the bindings manually
this._cd.detectChanges();
}