Why calling detectChanges() inside component doesn't update values, but wrapping code in setTimeout() does it?

kav picture kav · Jan 2, 2018 · Viewed 12.3k times · Source

I'm trying to automatically select the first value from set of options in <mat-autocomplete ...>

export class ExampleComponent implements OnInit, AfterViewInit {

@ViewChildren('auto') matAutocomplete: QueryList<any>;

constructor(private cdr: ChangeDetectorRef) { }

ngAfterViewInit() {
    this.foundItemsList.changes.subscribe(options => {
        // ---> This simply works!
        setTimeout(() => this.matAutocomplete.first._keyManager.setFirstItemActive(), 0);

        // ---> This doesn't works?! No error shown, it just seems that the above function isn't called at all. 
        this.matAutocomplete.first._keyManager.setFirstItemActive()
        this.cdr.detectChanges();
    });
}

https://github.com/angular/material2/blob/master/src/lib/autocomplete/autocomplete.ts

AFAIK, what detectChanges does is check the change detector of current component and all of its children components, correct? But it seems that it's not working in the scenario above.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jan 2, 2018

this.cdr.detectChanges() only runs change detection for the current component (and descendants). If setFirstItemActive() causes changes elsewhere this is not covered. setTimeout() or zone.run(...) or ApplicationRef.tick() causes change detection to be run for the whole application and therefore every binding is covered, not only the current component.