4

If I have scrolled down on a page where multiple elements have been generated on *ngFor, clicking on an element brings me to a different page via the router. When I click on a button to get back to the previous page, I would like the screen to be scrolled down to the position I was in before I left the page.

How can I achieve this?

j-meiring
  • 71
  • 4

1 Answers1

1

Let's suppose List page has ngFor loop like:

<div *ngFor="let note of (noteService.notes | async); let i = index" class="item" tabindex="0">
  <a (click)="edit(note, i, $event)">
    {{note.text}}
  </a>
</div>  

In edit function, it provides additional index into url like ...?i=11:

this.router.navigate(['group', this.noteService.groupName, 'edit', note.$key],
  { queryParams: { i: index } }); // pass in additional index in ngFor loop

Edit page remembers index as this.noteIndex in ngOnInit, then when going back:

this.router.navigate(['group', this.noteService.groupName],
  { queryParams: { i: this.noteIndex } }); // to let List page focus this note

Then List page's ngOnInit can do below:

this.noteService.announcedCountNotes.subscribe(
  count => {
    // noteService announces new count after it saves edit
    // so by now, ngFor should be ready
    if (idxToFocus) { // this.route.snapshot.queryParams['i'];
      setTimeout(_ => {
        var elements = document.querySelectorAll('div.item');
        var len = elements.length;

        if (len > 0 && idxToFocus >= 0 && idxToFocus < len) {
          const el = elements[idxToFocus] as HTMLElement;
          //el.scrollIntoView();
          el.focus();
        }
      }, 0);
    }
  }
)

You might want to provide specific style for div.item:focus, this way worked at least on Chrome 59 (Windows 7 and iPad) for me.

bob
  • 2,674
  • 1
  • 29
  • 46