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

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

How to fix patchValue not functioning in an angular formArray?

Inside my Angular application, I am creating a formArray within a form. However, when I try to patch an object containing tasks with values as an array, it seems that this property is being ignored and not set. Interestingly, the first name is changed as ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

The use of dates (YYYY-MM-DD) as identifiers in HTML/Angular 2 is causing issues

I have successfully created a calendar using html in Angular 2, and now I am looking to incorporate events into it. These events should be able to color specific days, add a dot inside the cell, or something similar. I have a json file that contains the ev ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

React: Selecting Component Name Based on Provided Property

My goal is to dynamically load an icon component in React passed as a prop from the parent component. Dashboard (parent): import { Button } from './components'; function App() { return ( <div className="app"> <d ...

Increment counter when a key is pressed in Angular 4 and decrement when the backspace key is pressed

As a beginner in Angular, my goal is to create a feature where: The character count in a label increases as text is entered into a textarea. When the backspace key is pressed, the counter should decrease. If the user attempts to enter more characters tha ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

Dynamically insert the ng-if attribute into a directive

In my code, I have implemented a directive that adds an attribute to HTML elements: module1.directive('rhVisibleFor', function ($rootScope) { return{ priority: 10000, restrict: 'A', compi ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

Sharing VueJS router with child component

How do I pass the router to my child component? This is my current router setup: import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) export default function () { const Router = new VueRouter({ mode: ' ...

Using PHP, JavaScript, and Bootstrap to display success or error messages for form fields through AJAX

I am working on a form where users input an 'authorisation code' that is then checked against a database using AJAX and PHP. Currently, the form displays a tick if the code is valid and a cross if it is incorrect. I would like to utilize Bootstra ...

Encountered an error stating "Cannot find module node:fs" while using eslint-typescript-import, eslint-import-resolver-typescript,

Challenge My attempt to configure path alias in my TypeScript project was met with failure. Two errors arose during the execution of npm start: Module not found: Error: Can't resolve '~/App' in 'D:\work\workbench\templa ...

How to incorporate JSON into a d3.js calendar display?

Learning d3 charts and javascript has been quite challenging for me. After researching a lot, I successfully populated the chart with CSV data. Now, my next goal is to populate the chart with json data. This is the code I'm using, which is inspired ...

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

What is the purpose of storing JSON data as a string within another JSON object?

Screenshot of developer tools While exploring the local storage on my visit to YouTube, I came across some very peculiar-looking JSON data. { creation: 1638112285935, data: "{\"quality\":1080,\"previousQuality&bs ...