Stencil Router Events or How to listen location changes

If you would take a look to Stencil Router documentation, you wouldn't find any info neither about open nor close page events, so how we would listen to them?

Stencil Router Events or How to listen location changes

If you would take a look to Stencil Router documentation, you wouldn't find any info neither about open nor close page events, so how we would listen to them? I made a simple library for this purpose.

Let's say we have an application compiled by Stencil which contains more than one page. Now, we want to add Google Analytics on our pages. Let's see how we can implement this goal.

Here's a standard stencil router configuration:
stencil-default-router

Nothing special, we just provide some props to a stencil-route component, in order to dynamically generate our app-home and app-about components based on History links. More about how to set up a stencil router, check this article.

Now, let's install ip-stencil-route-listener library and make some changes:

npm i ip-stencil-route-listener

After install, we have to add <ip-stencil-route-listener /> component inside of routeRender function of <stencil-route />. Take a look to red lines:
stencil-route-listener-1

Nothing much! Now each time when you enter or leave a page, the EventListener will trigger pageEnter or pageLeave events. The names of these events talk about their selves.

Take a look at this image:
stencil-listen-page-events-1

So, let's add Google Analytics on pageEnter event:

  @Listen('pageEnter')
  onPageEnter(e: CustomEvent<LocationSegments>) {
    // This is a Goolge Analytics event
    (window as any).ga('send', 'pageview', e.detail.pathname);
  }

Here is an example of this demo.

Consider using this library until there will be some official events support delegated by stencil router. I reckon they will implement kind of these very soon.