单击链接后,我想导航到不同页面/组件的片段。尽管尝试了多种方法,我还是没能做到这一点:
链接:
<a routerLink="/main/dash" fragment="dir">View</a>
目的地html/template:
<!-- Other elements -->
<app-dir id="dir"></app-dir>
路由器配置:
{
path: 'main',
component: LayoutComponent,
children: [{
path: 'dash',
loadChildren: () => import('src/app/features/dash/dash.module').then(m => m.DashModule),
canActivate: [AuthGuard]
}]
// Other code
}
// Other code
imports: [RouterModule.forRoot(appRoutes, { useHash: true, anchorScrolling: 'enabled', onSameUrlNavigation: 'reload' })],
点击";查看";链接,系统导航到/main/dash
路径/页面/组件,但第一次不会滚动到片段。一旦我进入主页,当我点击同一个导航链接(视图-位于标题中(时,它就会滚动到片段。
例如,当我已经在同一个页面/组件上时,AnchorScrolling可以工作,但如果源是不同的页面/组件,则不能工作。
我还尝试使用CCD_ 2&this.router.navigate()
而不是使用routerLink,但结果是一样的。
我确实使用HashLocationStrategy
。
如有任何帮助,我们将不胜感激。
谢谢!
更新:
经过更深入的挖掘,页面加载后的片段路由角度正是我面临的问题。似乎还没有可用的解决方案?:https://github.com/angular/angular/issues/30139
我也遇到了同样的问题。有趣的是,一旦导航到带有碎片的页面,它就会滚动到底部。以下是对我有效的解决方案:
在包含碎片的组件中:
/*...imports*/
export class ComponentWithFragmentsInTemplate implements OnInit, AfterViewInit {
private fragment: string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.route.fragment.subscribe(fragment => {
this.fragment = fragment;
});
}
ngAfterViewInit(): void {
setTimeout(() => { //I needed also setTimeout in order to make it work
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) {
}
});
}
没有空的setTimeout()
,它对我不起作用。