Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 718
Kristian Vitozev Avatar asked Jan 02 '18 14:01

Kristian Vitozev


1 Answers

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.

like image 58
Günter Zöchbauer Avatar answered Oct 22 '22 08:10

Günter Zöchbauer