【问题标题】:Navigate to a fragment of a **different** (not the same) page/component in Angular导航到 Angular 中**不同**(不相同)页面/组件的片段
【发布时间】:2020-11-05 13:27:42
【问题描述】:

点击链接后,我想导航到不同页面/组件的片段。即使尝试了多种方法,我也无法做到这一点:

链接:

<a routerLink="/main/dash" fragment="dir">View</a>

目标 html/模板:

<!-- 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 有效,但如果源是不同的页面/组件,则不是。

我也尝试使用 (click)this.router.navigate() 而不是使用 routerLink - 但结果是一样的。

我确实使用HashLocationStrategy

任何帮助将不胜感激。

谢谢!

更新:

在深入挖掘之后,Fragment Routing after Page Load Angular 正是我面临的问题。好像还没有解决方案?:https://github.com/angular/angular/issues/30139

【问题讨论】:

标签: angular angular-routing anchor-scroll page-fragments hash-location-strategy


【解决方案1】:

我遇到了同样的问题。有趣的是,一旦导航到带有片段的页面,它就会滚动到底部。 这是对我有用的解决方案:

在包含片段的组件中:

/*...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() 它对我不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多