Angular 2 Routing and links behavior

Issue

I would like to ask about angular 2 – 5 routing.

I think as its single page application when I use routing i found the behavior of the links is not the same as normal application cause the page not reloading.

when you click link in the middle of the page the route change the DOM but you stay in the same point of the page. ( not go to the top as normal application )

so is that is normal ? or there is something I miss about this ?

Solution

This is normal in angular 5. However if you want to change this behaviour, you can listen to route changes and scroll to top.

Guilherme Meireles provides code for doing this:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((e) => {
            if (!(e instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}

Answered By – Shrey Kejriwal

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.