2017-08-17 65 views
2

點擊一個按鈕(這是頁面的底部),我想要去一個特定的元素(在我的情況下,#navbar),這是在當前頁面,但我不知道該怎麼做。我已經嘗試了下面的代碼無濟於事。滾動到Angular 4當前頁面的某個元素

<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> 

在角度成分:

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

我真的很感激,如果有人幫了我一個解決方案,並解釋了爲什麼我的代碼沒有工作。

請注意,元素(導航欄)位於其他組件中。

+0

它不會達到我的目的。我想使用點擊事件。也希望遵循嚴格的角度慣例。 – asmmahmud

+0

從什麼時候Angular剝奪了你的約定HTML?這是沒有道理的,但尊重你的選擇 – Vega

回答

3

您可以用JavaScript做到這一點:

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

這將使DOM元素與id="navbar"進入視野時,方法被調用。還有使用Element.scrollIntoView的選項。這可以提供流暢的動畫並且看起來不錯,但在舊版瀏覽器中不受支持。

如果元素位於不同的組件中,您可以參考this question中的幾種不同的方法。

對於你的情況,最簡單的方法很可能是:

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.

+0

它似乎沒有工作。請注意元素在其他組件中。 – asmmahmud

+0

已更新的答案包含https://angular.io/api/core/ElementRef –

+0

仍然無效。 – asmmahmud

0

我想用自己的方式並未因爲空路由器的工作。

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

如果將'home'聲明爲路由並且其上具有id =「top」元素,則可以工作。

我知道你想它是「純角路」,但這應該工作(至少):

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

我知道了,你要滾動到網頁中的特定元素。但是,如果元素位於頁面頂部,則可以使用以下內容:

window.scrollTo(0, 0); 
相關問題