在使用Angular 10中,如果给一个带有position: absolute
和overflow: auto
样式的div上的Router的anchorScrolling不起作用,可以尝试以下解决方法:
RouterModule.forRoot()
方法配置路由时启用了anchorScrolling
选项。示例代码如下:import { NgModule } from '@angular/core';
import { RouterModule, Routes, Scroll } from '@angular/router';
const routes: Routes = [
// 路由配置
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
anchorScrolling: 'enabled', // 启用anchorScrolling选项
scrollPositionRestoration: 'enabled',
scrollOffset: [0, 64], // 如果有固定的导航栏,可以设置偏移量
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
position: absolute
和overflow: auto
样式的div上,添加scrollable
属性。示例代码如下:
ScrollingService
,并调用scrollIntoView()
方法手动滚动到指定的锚点。示例代码如下:import { Component, OnInit, ElementRef } from '@angular/core';
import { ScrollingService } from '@angular/cdk/scrolling';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
constructor(private scrollingService: ScrollingService, private elementRef: ElementRef) { }
ngOnInit(): void {
const element = this.elementRef.nativeElement.querySelector('#your-anchor-id');
this.scrollingService.scrollIntoView(element);
}
}
以上是一些可能的解决方法,根据具体情况选择适合的方式。
上一篇:Angular 10:CommonJs 和 AMD 依赖可能导致优化中断,hotkeys.js 依赖于 'mousetrap'。
下一篇:Angular 10:Firestore(7.19.1):无法连接到Cloud Firestore后端。后端在10秒内没有响应。