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

2

18

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.

Pentha answered 2/1, 2018 at 14:1 Comment(0)
O
15

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.

October answered 2/1, 2018 at 14:6 Comment(3)
Is there any reference on what zone.js does?Oberon
google.at/…. It just creates a new scope for the Angular code where (almost) all async APIs are are patched, so that Angular gets notified when an async call has completed.Ameeameer
@sabithpocker, check Do you still think that NgZone (zone.js) is required for change detection in Angular?Silage
E
7

Watch out if you're using content projection (ng-content) or @HostBindings.

When you run change detection for the component hosting the content, or setting the host binding it may not actually take effect because it is the parent component (which may be in a different module even) that 'owns' those attributes.

However, the behavior related to markForCheck() was changed in May 2017 to mark for check the projected ng-content in the parent component. https://github.com/juleskremer/angular/commit/f894dbdd78cf463ed53b6c50d883326ff7fbff87

It seems therefore that detectChanges() is insufficient for included content and you should use markForCheck instead which will trigger the included content to be checked.

Estrada answered 21/8, 2018 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.