Angular 4 中滚动到当前页面的某个元素

Scroll to a certain element of the current page in Angular 4

单击按钮(页面底部)后,我想转到当前页面顶部的某个元素(在我的例子中,#navbar),但我不知道怎么做。我尝试了以下代码但无济于事。

<nav class="navbar navbar-light bg-faded" id="navbar">
    <a class="navbar-brand" href="#">
        {{appTitle}}
    </a>
    <!-- rest of the nav link -->
</nav>
<!-- rest of the page content -->

<!-- bottom of the page -->
<button class="btn btn-outline-secondary" (click)="gotoTop()">Top</button>

在 angular 组件中:

import { Router } from '@angular/router';
 /* rest of the import statements  */
export class MyComponent {
   /* rest of the component code */
    gotoTop(){
       this.router.navigate([], { fragment: 'navbar' });
    }
}

如果有人能帮助我解决问题并解释为什么我的代码不起作用,我将不胜感激。

请注意元素(导航栏)在其他组件中。

您可以使用 javascript:

gotoTop() {
  let el = document.getElementById('navbar');
  el.scrollTop = el.scrollHeight;
}

这将在调用该方法时将带有 id="navbar" 的 DOM 元素显示在视图中。还有使用 Element.scrollIntoView 的选项。这可以提供流畅的动画并且看起来不错,但在旧版浏览器上不受支持。

如果该元素位于不同的组件中,您可以通过多种不同的方式引用它,如 中所示。

最适合您的情况的方法可能是:

import { ElementRef } from '@angular/core'; // at the top of component.ts

constructor(myElement: ElementRef) { ... } // in your export class MyComponent block

最后

gotoTop() {
  let el = this.myElement.nativeElement.querySelector('nav');
  el.scrollIntoView();
}

Working plunker.

我认为你的方法不可行,因为路由器是空的。

this.router.navigate(['/home'], { fragment: 'top' });

如果 'home' 被声明为路由并且你有 id="top" 元素就可以工作。

我知道你希望它是 "pure Angular way",但这应该有效(至少):

gotoTop(){
  location.hash = "#navbar";
}

我知道,您想滚动到页面中的特定元素。但是,如果元素位于页面顶部,则可以使用以下内容:

window.scrollTo(0, 0);
document.getElementById("YOUR_DIV_ID").scrollIntoView({ behavior: 'smooth' });