Move to the top of the page when the next action is activated

I am working with an Angular 8 application.

Within the application, I have implemented navigation buttons for next and previous actions.

My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page rather than where the previous state left off. To achieve this, I attempted to utilize the following code:

nativeElement.scrollTo(0, 0);

Unfortunately, this approach resulted in an error being thrown.

The navigation links related to this issue can be found within the EcheqProcessComponent component:


 <app-echeq-page #scrollMe
      *ngIf="!submitting"
      [currentEcheqPage]="currentEcheqPage"
      [currentEcheqPager]="currentEcheqPager"
    ></app-echeq-page> 

 <app-echeq-progress-nav
      *ngIf="!submitting"
      [currentPage]="currentEcheqPageIdx + 1"
      [totalPages]="currentEcheqPath.length"
      (next)="next()"
      (previous)="prev()"

      [isbtnDisabled]="currentEcheqSubmission?.status === EcheqSubmissionStatus.EXPIRED"

      [conditionals]="{
        isFirst: currentEcheqPager.isFirst,
        sending: sending
      }"
    ></app-echeq-progress-nav>

The paging behavior specific to navigating to the top of the page is addressed in the EcheqPageComponent:


export class EcheqPageComponent implements OnInit, AfterViewInit {
  @ViewChild('scrollMe', { static: false }) private contentPageRef: ElementRef;
  @Input() currentEcheqPage: EcheqPage;
  @Input() currentEcheqPager: EcheqPager;
  // We use template variables to query the components
  @ViewChildren('echeqElement') elementComponents: QueryList<EcheqElementComponent>;

  EcheqElement = EcheqElement;
  elementsChanged = true;

  constructor(private echeqService: EcheqService) {}

  ngOnInit() {}

  ngAfterViewInit() {
    this.scrollOnTopPage();
  }


  private scrollOnTopPage(): void {
    this.contentPageRef.nativeElement.scrollTo(0, 0);
  }
}

However, attempting to implement this solution led to the following error:

echeq-process.component.html:13 ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at EcheqPageComponent.push../src/app/echeq/echeq-page/echeq-page.component.ts.EcheqPageComponent.scrollOnTopPage (echeq-page.component.ts:79)

I tried adjusting certain elements in the markup as suggested below:

<app-echeq-page #scrollMe
      [hidden]="submitting"
      [currentEcheqPage]="currentEcheqPage"
      [currentEcheqPager]="currentEcheqPager"
    ></app-echeq-page>

Additionally, I made changes like this:

 <app-echeq-page #scrollMe
     *ngIf="!submitting"
      [currentEcheqPage]="currentEcheqPage"
      [currentEcheqPager]="currentEcheqPager"
    ></app-echeq-page>

and also introduced a delay using setTimeout:

  ngAfterViewInit() {
    setTimeout(() => {
       this.scrollOnTopPage();
    }, 1000) ;
 }

Despite these adjustments, the error persisted:

core.js:7376 ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at EcheqPageComponent.push../src/app/echeq/echeq-page/echeq-page.component.ts.EcheqPageComponent.scrollOnTopPage (echeq-page.component.ts:81)
    at echeq-page.component.ts:29
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:26760)
    at 

The structure of the large EcheqPageComponent.html file complicates resolving this issue:

<div class="echeq-page">
  <h4 class="echeq-title">{{ currentEcheqPage.title }}</h4>

...(omitting rest of the content for brevity)...

</div>

Answer №1

Make sure to also verify the submission in the component:

export class EcheqPageComponent implements OnInit, AfterViewInit  {
  @ViewChild(EcheqPageComponent, { static: false, read: ElementRef }) private contentPageRef: ElementRef<EcheqPageComponent>;
  ...

  ngAfterViewInit() {
    this.scrollToTop();
  }

  private scrollToTop() {
    if(!this.submitting) {
      this.contentPageRef.nativeElement.scrollTo(0, 0)
    }
  }
}

Additionally, apply styling to the EcheqPageComponent component as it may be necessary for proper scrolling functionality.

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

Node.js can be used to easily set the values of HTML elements

After successfully setting up a node.js connection to my mysql database and being able to retrieve and input data using connection.query(), I now want to display the database information on my HTML elements. Is there an equivalent of getElementById for t ...

After installing Node.js on a Windows machine, the program 'npm' is not identified as an internal or external command, and cannot be executed as an operable program or batch file

I have been searching for a solution to this problem, but none of the suggestions I found seem to work for me. I am currently using a Windows 10 Laptop where I do not have administrative rights. My goal is to run my Angular + NodeJS application on this ma ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

What is the best way to dynamically insert content into a PDF using pdfmake?

In my quest to dynamically generate PDFs using pdfmake, I've encountered an issue with creating dynamic rows based on data. To illustrate, here is a simplified version of the code: getDocumentDefinition(img: string, data: DataResponse, user: UserResp ...

What is the proper way to implement v-model for a custom component within the Vue render function?

Below is the code that I am working with: ... var label_key_map = { a: "1", b: "2", c: "3", d: "4" } render: (h) => { var form_data = {} for (let key in label_key_map) { var form_item = h( 'FormItem', {props: {prop: key}}, ...

JavaScript - Attempting to Add Objects to Array Unsuccessful

After seeing this question raised multiple times, I am determined to find a solution. In my current project, I am tasked with displaying a list of orders and implementing a filter by date functionality. However, I keep encountering an error when trying to ...

What is the best way to invoke a function in a specific child component from its parent component?

It seems that I might have provided too much information, but the main question remains: how can I call a method in the child component from the parent template's click() event. <button(click)='get()'>GET</button> In my case, th ...

A more efficient approach to specifying types for the 'navigation' object in React Native's Stack Navigator

Struggling with modularizing prop types in React Navigation, particularly when using TypeScript. The Typescript section of the React Navigation documentation suggests defining types for each screen props in this manner: //types.ts export type RootStackPara ...

Avoid displaying passwords in source code

Currently, I am working on developing a password manager web application similar to LastPass. One issue that has come to my attention is the visibility of variables containing decrypted passwords in the source code after retrieving them from a database u ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

The output of switchMap inner will generate an array similar to what forkJoin produces

I have a series of observables that need to run sequentially, with each result depending on the previous one. However, I also need all the intermediate results in an array at the end, similar to what is achieved with the use of forkJoin. Below is the curr ...

Encountering an issue while attempting to make an in-app purchase with Ionic 3 and Cordova - receiving the error message "Sorry, the item you are trying to

In the process of developing my app with IONIC 3 and Angular 4, I have integrated the following Ionic plugin for in-app purchases: https://ionicframework.com/docs/native/in-app-purchase/ Once the plugin was installed, I included the "play_store_key" in t ...

Retrieving data from a JSON file depending on the selection made by the user in a dropdown menu

In my project, I have a JSON file named countries.json that contains country and regional information. Users are required to select a country using a Python-generated dropdown list from this file. However, due to the backend nature of Python, I am unable t ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

Fetching user feeds from Facebook with AngularJS is easier than you think

I have searched through multiple articles but have yet to find a solution for this particular issue. My goal is to retrieve user feeds from Facebook. How can I achieve this? Below is my code: var newMod = angular.module('newapp', []); newMod.c ...

Encountered an error while attempting to insert a new user into a MySQL database using the Node, Express, and MySQL package

Currently in the process of creating a CRUD API using NodeJS. My main goal at the moment is to execute a POST request to add a new user to the database. The issue I am facing is that although I can successfully add a new user to the database, my server cra ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...