如果我向下滚动了在* ngFor上生成了多个元素的页面,单击一个元素会通过路由器将我带到另一个页面。 当我点击按钮返回上一页时,我希望屏幕向下滚动到我离开页面之前的位置。
我怎样才能做到这一点?
答案 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)。