What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead.

Is there a way to achieve this? Check out the code in the link below for reference:

https://stackblitz.com/edit/angular-material-router-mra2ke?file=src/app/plain/plain.component.ts

Answer №1

To ensure the existing code functions correctly, you need to take two steps:

  • Remember that component variables are lost when the component is destroyed. Instead of using the component variable to store the current position, utilize browser storages like sessionStorage/localStorage or a variable from shared service, and set the id to the rows. Here's an example of how to achieve this:
  get elementClickedId() {
    return sessionStorage.getItem('elementClickedId');
  }

  set elementClickedId(id) {
    sessionStorage.setItem('elementClickedId', id);
  }

Assign the id in your HTML:

<td mat-cell *matCellDef="let element" [id]="element.position">
   {{ element.position }}
</td>
  • Instead of calling moveToSection in ngOnInit, move it to ngAfterViewInit since the view is not initialized when trying to do document.getElementById.

Check out a working example here: https://stackblitz.com/edit/angular-material-router-eo6wnt?file=src/app/plain/plain.component.ts

PS: Angular provides a navigation config option called scrollPositionRestoration which can help with this issue. However, there may be cases where it doesn't work as expected due to a known defect - https://github.com/angular/angular/issues/24547

Answer №2

To maintain the current position, it is recommended to use a singleton service:

(While localStorage or sessionStorage can also be used, using a singleton service is preferred for better efficiency!)

@Injectable({
  providedIn: 'root',
})
export class ApiService {
  elementClickedId:any;
}

Additionally, ensure to assign an id to your td element:

<td mat-cell *matCellDef="let element" id={{element.position}}>{{ element.position }}</td>

Replace ngOnInit with ngAfterViewInit to guarantee that the scroll is set after the table rendering is completed.

For a functional example, you can refer to this StackBlitz project I've prepared for you: StackBlitzForked

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

Using ASP.net MVC 4 to Implement Validation with Bootstrap Modal and PartialView

After switching from a simple View with validation to using a bootstrap modal and PartialView in my application, I encountered some issues. The client-side validation no longer works and the server-side validation redirects me to a new page instead of disp ...

Is there a way for me to retrieve the value from an input, round it up to the nearest even number, and assign it to a new variable?

I am working on a project that involves two text boxes and a drop-down menu for providing rates. The values in the text boxes are given as inches. I want these inputs to be taken as values, rounded up to the next even number, and then set as variables. How ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Why does the private map function in the class fail while the global function succeeds?

Issues arise when calling the map() function on a parsed JSON object within the mapStocks() function. Placing the toStock() function inside the StockService class results in failure, whereas declaring it as a "global" function outside the class works witho ...

What makes Next.js API so special?

As I delve into Next.js, I find myself grappling with the concept of server-side rendering (SSR) and API usage. When is it appropriate to utilize the API folder within pages versus deploying my own server along with a database? Would there be any conflic ...

What are some strategies for getting neglected distribution files onto Bower despite being ignored by git?

I am in the process of creating a package for NPM and Bower. To maintain organization, I store my working files (ES6) in the src/ directory of the package and compile the distribution files (ES5, using Babel) in the lib/ directory. For version control, I ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

Is the button failing to direct you to the intended destination?

I'm facing an issue with a button tied to a JavaScript function using onClick(); My interface allows me to ban players on a game server, but when I select anyone here: https://i.stack.imgur.com/kcE1t.png, it always selects wartog for some reason. In ...

Updating JSON data within JavaScript

Currently, I am in the process of developing a webpage that pulls data from a json feed. However, I am looking to have it update every 30 seconds without refreshing the entire page, just refreshing the Div & Jquery elements. I have attempted various solut ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

"An error occurred while trying to retrieve memory usage information in Node.js: EN

Is there a way to successfully run the following command in test.js? console.log(process.memoryUsage()) When running node test.js on my localhost, everything runs smoothly. However, when attempting to do the same on my server, I encounter this error: ...

Navigating to a Different Page in Angular 7

After logging in on my login page, the dashboard component appears below the login page instead of redirecting as a new page. How can I achieve this in Angular 7? Any assistance would be greatly appreciated. Thank you! app.component.ts import { Component ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

Deliver a communication from the dialogue box on the MEAN stack website to the task pane

Currently experimenting with the Dialog API within Office addins. Able to successfully trigger a Dialog box from my task pane using: $scope.openDialog = function () { Office.context.ui.displayDialogAsync('https://localhost:3000/home', ...

An issue occurred when retrieving the input value during a (change) event within a nested *ngFor loop in Angular

Within my table, I have implemented a nested loop using the *ngFor directive: <tbody> <tr *ngFor="let dept of salesTarget; let i = index"> <td>{{dept.dept}}</td> <td *ngFor="let month of monthList; ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

The innerHTML function in jQuery seems to be malfunctioning

My div isn't displaying the expected content. This is my controller action: /// <summary> /// GetCountiresForManufacturer /// </summary> /// <returns></returns> [Authorize(Roles = "Administrator")] [Ac ...

How can I dynamically update the sidebar in Ionic 3 post-login without the need to reload the app or refresh the browser?

I have successfully implemented login and sign up functionality in my ionic 3 app. However, I am facing an issue where the username is not updating in the sidebar instantly after logging in. Currently, I need to refresh the browser or close and reopen the ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

Ensure that everything within the Container is not see-through

Fiddle:https://jsfiddle.net/jzhang172/b09pbs4v/ I am attempting to create a unique scrolling effect where any content within the bordered container becomes fully opaque (opacity: 1) as the user scrolls. It would be great if there could also be a smooth tr ...