导航到动态Angular 2页面上的指定位置

时间:2017-02-21 13:52:09

标签: html angular angular2-routing ngfor anchor-scroll

如果我向下滚动了在* ngFor上生成了多个元素的页面,单击一个元素会通过路由器将我带到另一个页面。 当我点击按钮返回上一页时,我希望屏幕向下滚动到我离开页面之前的位置。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

假设List页面的ngFor循环如下:

<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>  

edit函数中,它为网址提供了额外的索引,例如...?i=11

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

Edit页面会将this.noteIndex中的索引记为ngOnInit,然后返回时:

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

然后List页面ngOnInit可以执行以下操作:

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);
    }
  }
)

您可能希望为div.item:focus提供特定的样式,这种方式至少适用于Chrome 59(Windows 7和iPad)。