您应该像这样创建一个顶级延迟加载路由:
{
path: 'my-items',
loadChildren: () => import('./pages/my-items/my-items.module').then(m => m.MyItemsModule)
}
然后使用 Angular CLI 创建一个新的路由模块,如下所示:
ng generate module pages/my-items/my-items --routing=true
这将创建一个包含 2 个模块文件的路由模块。其中一个模块文件包含 my-items 路由的子路由。
在这个模块文件中,你应该像这样定义你的子路由:
[
{
path: 'items',
component: ItemsComponent
},
{
path: 'item/:id',
component: ItemComponent
}
]
您显然需要创建这两个组件(ItemsComponent 和 ItemComponent),并且它们应该嵌套在使用它们的模块文件夹中。同样,您可以使用 Angular CLI 生成这些组件(如果您这样做并且它们按照说明嵌套,它应该自动在正确的模块中声明它们)。
ng generate component path/component-name
或
ng g c path/component-name
您可以在以下位置访问这些路线:
/my-items/items
与
/my-items/item/ITEM_ID
滚动:
在用户单击 BACK 时保持滚动位置:
在主视图中使用:
@ViewChild('scrollableEl ') scrollableEl: ElementRef;
然后在您的 HTML 中添加 #scrollableEl 到可滚动元素。
您现在有了可滚动元素的句柄。
然后做这样的事情:
ngAfterViewInit(): void {
const scrollEl: HTMLElement = this.scrollableEl.nativeElement;
// set last known scroll top value when master view loads
const strScrollTop: string = sessionStorage.getItem('scrollTop');
const scrollTop: number = strScrollTop ? parseInt(strScrollTop, 10) : 0;
scrollEl.scrollTop = scrollTop;
// keep track of the last known scroll position
scrollEl.onscroll = () => {
sessionStorage.setItem('scrollTop', scrollEl.scrollTop);
};
}
您无需向详细视图添加任何代码。
这个解决方案基本上会跟踪 sessionStorage 中最后一个已知的滚动位置。当主组件加载时,它将列表滚动到最后一个已知的滚动位置。我的代码没有经过测试,所以这里或那里可能有一个错误或 2 个错误,但你应该明白了。
根据评论的示例 SETINTERVAL 聪明代码
如果您的滚动元素在页面加载时还没有准备好,这是一些示例代码,可以在元素准备好后立即抓取它。它总是尽快清除间隔。您将需要定制此代码以满足您的需求。
@ViewChild('summaries') summaries: ElementRef;
ngAfterViewInit(): void {
this.doScroll();
}
@HostListener('window:resize')
onResize(): void {
this.doScroll();
}
private doScroll(): void {
this.whenElementReady('summaries').then((el: HTMLElement) => {
if (el) {
// change this to the scrollTop value that you need
el.scrollTop = 0;
}
});
}
private whenElementReady(elementName: string): Promise<HTMLElement> {
return new Promise((resolve) => {
// will keep trying for 30 seconds
const maxAttempts = 300;
let attempts = 0;
const interval = setInterval(() => {
const el: HTMLElement = this[elementName]?.nativeElement;
if (el) {
clearInterval(interval);
resolve(el);
} else if (attempts > maxAttempts) {
clearInterval(interval);
resolve(null);
}
attempts++;
}, 100);
});
}