Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as:

<about></about>
<contact></contact>

I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I am facing an issue with scrolling to the desired section upon application initialization.

When a user first opens the page with '/contact' in the route, I want it to automatically scroll down to the contact section instead of staying at the top.

In my implementation, I have included the following code snippet:

 if(this.router.url != '/') {
  let pageScrollInstance: PageScrollInstance = PageScrollInstance.simpleInstance(this.document, '#'+this.router.url.substring(1));
  this.pageScrollService.start(pageScrollInstance);
}

This code is placed inside the constructor, but it seems to execute before the router sets the route on 'router.url'.

I tried using 'window.location.href.split("/").pop()' to obtain the address before the router is set, but this triggers before the components are fully rendered, resulting in scrolling to the wrong position.

Is there a hook available that triggers once the entire app routing is set and everything is rendered?

Answer №1

Utilize this technique to save the NavigationEnd url in a variable within a service and access it throughout your entire application.

This method is beneficial when employed within the AppComponent to facilitate changes between URLs.

router.events.subscribe(event => {
      //if (event instanceof NavigationStart) {
        console.log('event', event)
      //}
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring scroll position remains fixed post screen rotation in HTML/Javascript

Is there a foolproof method to retain the scroll position in an HTML document following a screen rotation? While this issue is specifically in a Cocoa Touch UIWebView, it seems to be prevalent across different platforms. The standard practice appears to re ...

Error encountered while attempting to serialize React Fragment: Symbol value cannot be converted to a string

Encountering an issue while attempting to render a React.Fragment: Error Message: Cannot convert a Symbol value to a string Snippet of the code being passed to a component: render{ const block = { type : 'menu', className: &ap ...

The expanded interfaces of Typescript's indexable types (TS2322)

Currently, I am in the process of learning typescript by reimagining a flowtype prototype that I previously worked on. However, I have hit a roadblock with a particular issue. error TS2322: Type '(state: State, action: NumberAppendAction) => State ...

The object NativeModules from the 'react-native' requirement is currently empty

At the top of one of the node_modules utilized in my project, there is a line that reads: let RNRandomBytes = require('react-native').NativeModules.RNRandomBytes However, I've noticed that require('react-native').NativeModules ...

Phonegap app unable to process AJAX post request, functions properly in browser

My AJAX request is encountering issues specifically when tested on the Phonegap App using iOS10. The code I am working with is as follows and functions perfectly in a browser: if($.trim(firstname).length > 0 & $.trim(email).length > 0 & $.t ...

I am attempting to add a new row (div) for the invoice, but when I do so, the

Looking for a solution to repeat a row when clicking a button in order to utilize PHP for data manipulation? Check out the code snippet below: <!-- Table row --> <br><br> <div class="row"> <!--Product Table--> <div ...

"Fetching and Utilizing the Output Parameter from an API in Angular4: A Step-by-Step Guide

Working on a post method in an Angular 4 web app, I am able to save data to the database successfully. However, I am facing an issue where an ID (return value) is passed from the DB to the API for Angular as another function parameter. How can I retrieve t ...

triggering a method in an Angular controller using a Google API embedded in the view

Using the Google Places Details API, I have included a Google API with a callback function called initMap in the src attribute. Here is the code snippet: <div class="tab-pane active" id="timeline"> <p class="lead">Location</p> <hr& ...

What is the best way to leverage an existing user database and integrate user authentication into a fresh project?

I have recently taken on the task of revamping an established project by creating a brand new frontend from scratch. After careful consideration, I have opted to develop a straightforward Vue/Node.JS project. Within the current framework lies a Postgres d ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Ways to address the issue of duplicated names in input fields

Currently, I am utilizing a React Hook Form hook known as useFieldsArray. This hook is responsible for rendering an array of fields, each containing an object with the data that will be transmitted via the input. One interesting feature is the ability to ...

Is it possible to have Angular and Node.JS Express running on the same port?

It seems like I may have a duplicated question, but I'm struggling to figure out how to properly configure and run the frontend and backend together. I've looked into solutions on this and this questions, but I'm still confused. Currently, ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

Is it possible to modify the labels on CKEditor's toolbar elements?

Initializing CKEditor in the following manner: function init() { $( ".ckeditor" ).ckeditor( { format_tags: 'h3;p', toolbar: [ [ "Source", "-", "Bold", "Italic" ], [ "Link", "Unlink" ], [ "Blockquote", "F ...

Having trouble importing cubing.js into my discord bot running on node

When attempting to import the cubing.js module into my nodejs project for use in a discord.js bot, I encountered an error. The specific import causing issues was const {randomScrambleForEvent } = require('cubing/scramble'), resulting in 'Err ...

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

Conditional rendering with React.js in the DOM

Just starting out with React and encountering an issue with rendering using reactDom: index.js import ReactDOM from 'react-dom'; import A from 'components/A'; import B from 'components/B'; render(<A />, document.getEl ...