要解决“Angular Router 锚点滚动片段未创建正确的 URL。”的问题,可以按照以下步骤进行操作:
app.module.ts
文件中导入RouterModule
和ScrollingModule
:import { RouterModule, Scroll} from '@angular/router';
import { ScrollingModule } from '@angular/cdk/scrolling';
@NgModule({
imports: [
RouterModule.forRoot(routes),
ScrollingModule
],
...
})
export class AppModule { }
routerLink
指令来创建带有锚点的链接。例如,在导航菜单或侧边栏中:跳转到Section 1
app.component.ts
文件中,确保使用ScrollingModule
提供的ScrollDispatcher
和ViewportScroller
来处理锚点滚动:import { Component, OnInit, OnDestroy } from '@angular/core';
import { ScrollDispatcher, ViewportScroller } from '@angular/cdk/scrolling';
@Component({
...
})
export class AppComponent implements OnInit, OnDestroy {
constructor(
private scrollDispatcher: ScrollDispatcher,
private viewportScroller: ViewportScroller
) { }
ngOnInit() {
this.scrollDispatcher.scrolled().subscribe((scrollable: Scroll) => {
const anchor = this.viewportScroller.getAnchorPosition();
if (anchor) {
this.viewportScroller.scrollToPosition(anchor);
}
});
}
ngOnDestroy() {
this.scrollDispatcher.ngOnDestroy();
}
}
app.component.html
文件中,确保在需要滚动到的锚点元素上添加id
属性。例如:Section 1
这些步骤应该能够解决“Angular Router 锚点滚动片段未创建正确的 URL。”的问题,并确保正确创建锚点滚动的 URL。