为 Angular 独立路由器配置滚动恢复?

Ole*_*Ole 2 javascript typescript angular

Angular Router 能够配置路由器以恢复滚动,并且链接的文档提供了如何在加载数据时执行此操作的示例。

我们如何配置独立路由器以将路由器出口滚动到顶部?

从这个演示中可以看出,在没有任何配置的情况下,如果两个视图都有可以滚动到底部的内容,如果一个视图确实滚动到底部,则在跨组件导航时视口将保持这种状态。

https://stackblitz.com/edit/angular-adcsej?file=src%2Fmain.ts

Ole*_*Ole 12

当使用独立的 AngularbootstrapApplication功能为路由器提供该provideRouter功能时,可以将路由器配置为始终滚动回顶部。

const scrollConfig: InMemoryScrollingOptions = {
  scrollPositionRestoration: 'top',
  anchorScrolling: 'enabled',
};

const inMemoryScrollingFeature: InMemoryScrollingFeature =
  withInMemoryScrolling(scrollConfig);
bootstrapApplication(App, {
  providers: [provideRouter(routes, inMemoryScrollingFeature)],
});

Run Code Online (Sandbox Code Playgroud)

这是一个演示: https ://stackblitz.com/edit/angular-quflkz?file=src%2Fmain.ts

相关文档。

这个演示展示了如果不使用滚动恢复会发生什么。

https://stackblitz.com/edit/angular-adcsej?file=src%2Fmain.ts