Angular2 Hashtag路由到Anchor不会移动页面

Angular2 Hashtag routing to Anchor doesnt move page

所以我使用下面的 post 来弄清楚如何将片段添加到 url。

Angular2 Routing with Hashtag to page anchor

并且片段添加得很好,但是页面不会移动到生成的锚点。我尝试在目标 div 上同时使用 nameid 属性,但似乎都不起作用。

我正在使用 Angular 版本 2.0.0-rc.3 和路由器版本 3.0.0-alpha.6。

谢谢!

<a [routerLink]="[]" fragment="destination">Go TO DIV</a>

<div id='destination'>
    <h2>Destination</h2>
</div>

2 个元素之间有足够的 space 来判断页面是否实际移动。

如前所述,url 正确地将 #destination 添加到自身。

解决方法可能是在您的组件中编写一个函数,将 location.hash 设置为您要导航到的 div 的 ID。

<a (click)="goTo('destination')">Go TO DIV</a>

<div id='destination'>
    <h2>Destination</h2>
</div>

然后在你的组件中:

goTo(location: string): void {
    window.location.hash = location;
}

你也可以使用这个插件https://www.npmjs.com/package/ng2-page-scroll 它对给定的锚点进行动画滚动。

这对我有用:

首先,在 ngAfterViewChecked()...

中准备 MyAppComponent 自动滚动
import { Component, OnInit, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component( {
   [...]
} )
export class MyAppComponent implements OnInit, AfterViewChecked {

  private scrollExecuted: boolean = false;

  constructor( private activatedRoute: ActivatedRoute ) {}

  ngAfterViewChecked() {

    if ( !this.scrollExecuted ) {
      let routeFragmentSubscription: Subscription;

      // Automatic scroll
      routeFragmentSubscription =
        this.activatedRoute.fragment
          .subscribe( fragment => {
            if ( fragment ) {
              let element = document.getElementById( fragment );
              if ( element ) {
                element.scrollIntoView();

                this.scrollExecuted = true;

                // Free resources
                setTimeout(
                  () => {
                    console.log( 'routeFragmentSubscription unsubscribe' );
                    routeFragmentSubscription.unsubscribe();
                }, 1000 );
              }
            }
          } );
    }

  }

}

然后,导航至 my-app-route 发送 prodID 主题标签

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component( {
   [...]
} )
export class MyOtherComponent {

  constructor( private router: Router ) {}

  gotoHashtag( prodID: string ) {
    this.router.navigate( [ '/my-app-route' ], { fragment: prodID } );
  }

}

这个解决方法应该可以解决问题

<div [routerLink]="[]" fragment="destination">
  <a href="#destination">Go TO DIV</a>
</div>

这是一个对我有用的非常简单的解决方案:

在组件中,添加这个方法:

navigateTo(location: string): void {
// location will be a valid CSS ID selector; i.e. it should be preceded with '#'
window.location.hash = location;
setTimeout(() => {
    document.querySelector(location).parentElement.scrollIntoView();
  });
}

并且在视图中,<a> 标记将如下所示:

<a (click)="navigateTo('#destination')">Destination</a>

看到这里的所有解决方案后,我决定使用一个小而简单的指令。这是我最终得到的结果:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({ selector: '[appAnchorTo]' })
export class AnchorToDirective {
  @Input() target: string;

  constructor(el: ElementRef) { el.nativeElement.style.cursor = 'pointer'; }

  @HostListener('click', ['$event'])
  onClick() { document.querySelector(this.target).scrollIntoView(); }
}

我们的想法是创建一些灵活的东西,可以附加到页面上的任何元素。

用法:

<a appAnchorTo target="#my-link">My Insights</a>
<div appAnchorTo target="#my-other-link">My Customers</div>

并且不要忘记在您的模块之一上声明该指令:

@NgModule({
    ...,
    declarations: [
        ...,
        AnchorToDirective,
    ]
})

我发现 nmp 中提供了非常有用的插件 - ngx-scroll-to,对我来说非常有用。然而它是为 Angular 4+ 设计的,但也许有人会发现这个答案有帮助。