![](/img/trans.png)
[英]While parameter routing in angular 2, constructor injection prevents the page from loading
[英]Page is not loading from the top when routing in angular?
我的问题是 - 考虑有两个页面 A 和 B。如果我在页面 A 上并向下滚动页面并单击某个按钮导航到页面 B,页面 B 保持与我在页面中滚动的相同滚动 position A. 而不是这个,我希望页面 B 应该从顶部加载,无论我在前一页上滚动了多少。
应用程序路由.module.ts
const routes: Routes = [
{path:'', redirectTo:'home', pathMatch:'full'},
{path:'home', component: HomeComponent},
{path:'about', component: AboutComponent},
{path:'product', component: ProductComponent},
{path:'contact', component: ContactComponent}
];
app.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
如何解决这个问题?
我还尝试了一些解决方案,例如:
{scrollPositionRestoration:'启用'}
(激活)="onActivate($event)
window.scrollTo(0,0)
我尝试的所有这些事情都是从上一页(A 页)上滚动的 position 滚动到顶部(B 页)。 任何其他解决方案或我错过了什么?
试试这个:在您的组件 B HTML 中,将您的页面包装在<main>
中。 然后,在您的组件 B 中,
组件-b.ts
export class ComponentB implements AfterViewInit {
@ViewChild('main') main: ElementRef;
ngAfterViewInit() {
this.main.nativeElement.scrollTop = 0;
}
}
这应该在页面加载后将页面滚动到顶部。
这是我在容器AppComponent
中的做法:
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
let x = document.getElementsByClassName('mat-drawer-content');
if (x.length > 0) x[0].scrollTo(0, 0);
});
如果您使用 Angular 材料中的mat-drawer
,这将起作用。 如果您正在使用另一个滚动的 div 替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.