如果我在一个页面上向下滚动,在*ngfor上生成了多个元素,单击一个元素就会通过路由器转到另一个页面。
当我点击一个按钮回到前一页时,我希望屏幕向下滚动到我离开前的位置。
我怎样才能做到这一点?
最佳答案
假设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
函数中,它为url提供额外的索引,如...?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)起作用。