Html 角度2:加载页面时跳转到页面的特定元素

Html 角度2:加载页面时跳转到页面的特定元素,html,angular,Html,Angular,我想从一个页面导航到另一个页面,并直接跳到目标页面中间的一个控件。通常,我们可以在控件的名称或ID后面使用标签“#” 然而,这种方法在Angular 2中确实非常有效。我试过这样的方法 . 使用这种方法,url确实以“#myId”结尾,但页面实际上不会跳转 我们有其他方法来实现这一点吗?Angular documentation project提供AutoScrollService服务。你可以试着使用它 /** * A service that supports automatically s

我想从一个页面导航到另一个页面,并直接跳到目标页面中间的一个控件。通常,我们可以在控件的名称或ID后面使用标签“#”

然而,这种方法在Angular 2中确实非常有效。我试过这样的方法 . 使用这种方法,url确实以“#myId”结尾,但页面实际上不会跳转


我们有其他方法来实现这一点吗?

Angular documentation project提供AutoScrollService服务。你可以试着使用它

/**
 * A service that supports automatically scrolling elements into view
 */
@Injectable()
export class AutoScrollService {
  constructor(
      @Inject(DOCUMENT) private document: any,
      private location: PlatformLocation) { }

  /**
   * Scroll to the element with id extracted from the current location hash fragment
   * Scroll to top if no hash
   * Don't scroll if hash not found
   */
  scroll() {
    const hash = this.getCurrentHash();
    const element: HTMLElement = hash
        ? this.document.getElementById(hash)
        : this.document.getElementById('top-of-page') || this.document.body;
    if (element) {
      element.scrollIntoView();
      if (window && window.scrollBy) { window.scrollBy(0, -80); }
    }
  }

  /**
   * We can get the hash fragment from the `PlatformLocation` but
   * it needs the `#` char removing from the front.
   */
  private getCurrentHash() {
    return this.location.hash.replace(/^#/, '');
  }
}