Home > Enterprise >  How to set Scroll position near to mat row in Angular?
How to set Scroll position near to mat row in Angular?

Time:09-26

I have more than 20 records loaded to angular material table. When I click one row it navigates to a page. And when I hit back button it return to table page. The problem is when I click on last row of the table, the scroll position goes to the top. I just want to set scroll position near to the clicked row.

How do I achieve that and refer code in below link.

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

CodePudding user response:

You need to singleton service to keep the current position:

(Note we also can use localStorage or sessionStorage But using singleton service is highly recommended and it's better that using other way!)

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

And also you need to set id for your td:

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

And use ngAfterViewInit instead of ngOnInit to make sure after completion of rendering your table, you set the scroll.

Here is working sample I've created for you: StackBlitzForked

CodePudding user response:

You'll have to do two things to make the existing code work:

  • Component variables are lost when the component is destroyed. So instead of using the component variable to store the current position use browser storages like sessionStorage/localStorage or use a variable from shared service and set id to the rows. For example you can do something like:
  get elementClickedId() {
    return sessionStorage.getItem('elementClickedId');
  }

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

Set id within your html:

<td mat-cell *matCellDef="let element" [id]="element.position">
   {{ element.position }}
</td>
  • When you are trying to do document.getElementById the view is not initialized, so it's not being auto scrolled. So instead of calling moveToSection in ngOnInit, do it in ngAfterViewInit.

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

PS: Angular comes with navigation config scrollPositionRestoration that helps in achieving this. But unfortunately it doesn't work all the time, there's a defect for it - https://github.com/angular/angular/issues/24547

  • Related