Search code examples
javascriptangulardomroutesangular2-changedetection

Angular Change Detection on a route change


I have read some good articles on Change Detection in Angular and established somewhat good understanding of what it is and how it works. But every article I have read till now only focuses on Change Detection when some event happens on the component or when some input property changes etc. I haven't found any article yet which focuses on what happens when a route changes? How Change Detection works in that scenario? Also, does Angular pushes all HTML/DOM updates at once to the browser or does it keep feeding the browser constantly as soon as it finds any DOM update?


Solution

  • Routing doesn't trigger change detection. The only thing that it does specific to change detection is marking for check the router-outlet component being activated:

    @Directive({selector: 'router-outlet', exportAs: 'outlet'})
    export class RouterOutlet implements OnDestroy, OnInit {
        ...
        activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver|null) {
            ...
            // Calling `markForCheck` to make sure we will run the change detection when the
            // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
            this.changeDetector.markForCheck();
            this.activateEvents.emit(this.activated.instance);
        }
    

    Router is navigated by some event UI or other (setTimeout, XHR) etc. that is intercepted by NgZone and once the code finished executing change detection process kicks in.

    Also, does Angular pushes all HTML/DOM updates at once to the browser or does it keep feeding the browser constantly as soon as it finds any DOM update?

    It updates DOM element by element as it progress through each component. For the most comprehensive explanation of change detection read all the articles mentioned in: