liveBook · Manning

IterableDiffers

As explained in Pro Angular 16

IterableDiffers is an Angular service that locates factories capable of comparing iterable collections for changes.

IterableDiffers helps a structural directive detect collection changes without rebuilding its embedded views on every ngDoCheck call. Inject it into the directive, then call find(dataSource).create() in ngOnInit to obtain an IterableDiffer. section 15.3.4

Update only for additions

In ngDoCheck, call differ.diff(dataSource). A null result means there are no collection changes to process. Otherwise, forEachAddedItem supplies records whose item and currentIndex can be used to create embedded views. This implementation handles additions only; removals and moves need separate handling. section 15.3.4

...
ngDoCheck() {
    let changes = this.differ?.diff(this.dataSource);
    if (changes != null) {
        console.log("ngDoCheck called, changes detected");
        let arr: IterableChangeRecord<any>[] = [];
        changes.forEachAddedItem(addition => arr.push(addition));
        arr.forEach(addition => {
            if (addition.currentIndex != null) {
                this.container.createEmbeddedView(this.template,
                    new PaIteratorContext(addition.item, 
                        addition.currentIndex,
                        arr.length));
            }
        });
    }        
}
...

Shows the addition-only ngDoCheck implementation, including the null check and creation of embedded views from change records. section 15.3.4

How Pro Angular 16 covers it

How deep it goes
Traces injection, differ creation, comparison, and addition handling; leaves removal and move handling beyond the initial implementation.
Examples
Shows a collection-rendering directive creating views for newly added items and later extending the application with deletion.
What it assumes
Assumes familiarity with Angular directives and lifecycle hooks while showing how to obtain and use an iterable differ.
What you can do after
Apply it via Angular's IterableDiffers to detect additions and avoid rebuilding views when the collection has not changed.
How it connects
Connects IterableDiffers to structural directives, ngOnInit, ngDoCheck, IterableDiffer, IterableChanges, and embedded views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.