Deep dive into Angular Routing — Scrolling to top, Debugging and lot more.

Pardeep Jain
5 min readMar 9, 2019

--

Have you used jQuery or window object to scroll to the top of the page while navigation?
Have you ever confused about why your routes are not navigating properly?
Wanna debug your routing or ever thought of?
Offcourse like this there are so many questions related to routing which is undercover for so many developers (Like me 😜 till now). Don’t worry You will definitely learn so many things new today.

What all you gonna learn by the end of this blog 👀

  • How to Debug Routing/Navigation in Angular.
  • Scroll to Top on each navigation in Angular way.
  • Navigate to the Same page using Fragment (#Id) in Angular way.
  • Reloading the same page without refresh the whole application.
  • Navigation handling If the webpage has any errors while loading.

and much more …

and much more …

The main reason to blog this as I’ve seen many developers are not aware of features angular has, they keep mixing jQuery or some custom manipulation to handle their routing problems, for example, I have seen a number of questions like

Ask

  • How to

ENOUGH TALKING!! Let’s start

I assume you are aware of routing structure of Angular, Basics about how routing works in angular etc.

1. Debugging 👽 in Angular Routing/Navigation

Sometimes while navigation to some complex URL/route having some parameters/Query Params we get some errors like route doesn’t exist etc.

In these scenarios to debug where exactly the problem is to use enableTracing options of the router module.

The code you have to use is like below -

@NgModule({  imports: [      RouterModule.forRoot(routes, {         enableTracing: true      })  ]})export class AppRoutingModule {}

This will enable the all router logs and all its internal events to the developer console. By default options value is set to false.

TIP: Once you debug and sort out your problem always set it to false else your console will become too much messy with all the router logs (which you never want to see like this).

2. Scroll to Top

Seen number of question on StackOverflow. Many of them use jQuery to scroll to the top of the view, some of them using javascript document and set their position manually.

The best solution I’ve found so far is to use scrollPositionRestoration option of routing.

This option accepts three options which are -

  • disabled
  • enabled
  • top

By default option set is disabled (Which does nothing and let the flow normal as it is).

What this piece of code does it -

Whenever you navigate to any route page automatically scrolled up to the top(does the same thing like scroll position to [0,0]).

Another powerful option is enable. I use word powerful because it will automatically store and restore your router view position and set the web scroll position accordingly.

The enabled option will be the default in the future probably.

This option is very useful when the user is reading a loooonnnng paragraph and has to navigate on some another route so whenever he/she switch back to the previous route they don’t need to scroll again. This option trick in those cases.

3. Navigate to the Same page using Fragment (#Id) in Angular way.

Confusing part here is many developers got confused with

and

  • fragment routing (https://www.xyz.com/abc#first-block) of Angular.

let’s move forward with fragment routing.

The very first thing to do is set enable an anchorScrolling option in the router configuration. This is used to scroll to any element with the same ID name in like `#first-block` in the URL. For example, we have in our template of component MyComponent.

<a id="first-block">First Block content</a>

and we have too much content on the top and bottom of this line of code.

Now, Whenever we navigate to URL like below -

https://www.xyz.com/my-component#first-block

It will be scrolled down to that portion of content. This option is much useful when we need to display multiple blocks/sections on a single page.

4. Reloading the same page without refresh the whole application.

In general, you are not able to reload a route if you were already viewing it in Angular.

In case we need to do so we opt for hacky ways like either forcefully reloads webpage (which is against of SPA rule) etc.

Don’t worry not like early days of Angular, Now Angular routing has this new feature (after v5.1) onSameUrlNavigation under router configuration. which lets you reload page even if you are on the same page. We have two options for the same which are -

onSameUrlNavigation: 'reload' | 'ignore'

By default, the router will ignore this navigation.

Behind the scene -

Basically, after enabling reload option it will not initialize component again, or call component’s constructor again (Github issue for your ref.). If you are thinking so, SORRY you are wrong.

Basically, It will re-trigger the router events from where we can get and make functionality accordingly. Those router events may call depending on these three conditions -

paramsChange — whenever there are any changes in router Parameters.

paramsOrQueryParamsChange — whenever either params or Query params changes

always — always fire.

5. Navigation handling If the webpage has any errors while loading.

We generally faced such problem when we are navigating to some route and due to some code level bug/error angular stops navigation and send us back to root route.

To avoid such case new option urlUpdateStrategy has been introduced for router configuration which accepts two options -

urlUpdateStrategy?: ‘deferred’ | ‘eager’
  • 'deferred', the default one, updates the browser URL after navigation has finished.
  • 'eager', updates browser URL at the beginning of navigation so the URL will be updated even if the navigation fails. useful in such scenarios where we need to show an error message but need URL to be updated.

6. Scroll to specific height/place within the page without fragment.

Another awesome option you can configure in angular routing configuration is scrollOffset.

scrollOffset?: [number, number] | (() => [number, number])

This option will let you set the custom scroll position for your template. You need to pass X, Y coordinates as the number to set the position.

Example -

import { ViewportScroller } from '@angular/common';
@Injectable({ providedIn: 'root'})export class ScrollService { constructor( private viewportScroller: ViewportScroller ) { this.viewportScroller.scrollToPosition([100, 100]); }}

Conclusion

Here is the list of all available options including the options we already discussed.

It’s time to ask yourself what you learn new by reading the whole long blog. If there is anything you learn new clap to appreciate me. If you have any doubt/suggestion, See you there below in the comments section!

Closing notes ⛳

Thank you so much for reading the whole article.

I hope you really learn something new If so Encourage me by pressing and hold the 👏🏻 icon. I love to see and welcome your valuable comments if any.

Also, I strongly welcome all the suggestions if any.

| Share | Follow |

--

--

Pardeep Jain
Pardeep Jain

Written by Pardeep Jain

25 | Angular Developer | Stackoverflow Lover | Quora Writter | Punjabi | https://pardeepjain.tech/

No responses yet