Explain differ services for tracking custom object and list mutations.
Skip to solutionKEEP THE
hardFrontend
What is the purpose of the KeyValueDiffers and IterableDiffers services?
1.0k views
01
Understand the problem
performanceadvanced
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
KeyValueDiffers and IterableDiffers are low-level utilities used to detect changes in key-value maps and arrays respectively. They calculate granular additions, deletions, and moves, which is useful when writing high-performance custom directives.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Building a custom list change tracking directive using IterableDiffers
import { Directive, Input, DoCheck, IterableDiffers, IterableDiffer, inject } from '@angular/core';
@Directive({
selector: '[appTrackChanges]',
standalone: true
})
export class TrackChangesDirective implements DoCheck {
@Input() appTrackChanges!: string[];
private differs = inject(IterableDiffers);
private differ: IterableDiffer<string> | null = null;
ngDoCheck() {
if (this.appTrackChanges && !this.differ) {
this.differ = this.differs.find(this.appTrackChanges).create();
}
if (this.differ) {
const changes = this.differ.diff(this.appTrackChanges);
if (changes) {
changes.forEachAddedItem(record => {
console.log('Item added:', record.item, 'at index:', record.currentIndex);
});
changes.forEachRemovedItem(record => {
console.log('Item removed:', record.item, 'from index:', record.previousIndex);
});
}
}
}
}05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 86 of 121 decoded in the Angular track. One more won't hurt.