Let's say I have 100 divs on my screen generated by *ngFor
that takes values from my object that has data like
{A1: someObject, A2: someOtherObject..., J10: someOtherOtherObject}
I click on A1 and then on J10 and they switch their values. It changed to this:
{A1: someOtherOtherObject, A2: someOtherObject..., J10: someObject}
How do I force Angular to only refresh two divs only holding A1 and J10 values? I am using ChangeDetectionStrategy.OnPush
, in constructor I have cd.detach()
and only call cd.detectChanges()
whenever second click occurs. Judging from what I see and am able to understand, each div triggers their *ngIf
so every single one of them is recreated.
Is there anything I can do to either a) override what is being refreshed or b) choose what to detect changes against?
If you track the items in your list, *ngFor="let item of items; trackBy: trackById"
.
Then it will not render all the items again.
trackById = trackBy('id');
...
export function trackBy(field: string): (_index: number, item: any) => string | number {
return (_index: number, item: any) => {
if (!item) {
return null;
}
return item[field] as (string | number);
};
}