2016-10-09 83 views
11

嘗試使用以下語法滾動到錨點鏈接。滾動到錨點不工作

<a [routerLink]="['./']" fragment="test">Testing</a> 

和錨節點看起來像這樣

<div id="test"> 

當點擊了瀏覽器的地址欄中顯示的#TEST片段,但自動滾動不會發生。任何想法爲什麼它不滾動?

回答

2

我想滾動不是用角度2來實現的。我對類似問題的解決方案(滾動到錨點在同一頁上)是使用ng2-page-scroll

14

基於@vsavkin解決方法,並利用該片段被提供爲可觀察到的(使用 「@角/芯」: 「^ 2.3.1」):

class MyAppComponent implements OnInit{ 

    constructor(private route: ActivatedRoute) { } 

    ngOnInit() { 
    this.route.fragment.subscribe(f => { 
     const element = document.querySelector("#" + f) 
     if (element) element.scrollIntoView(element) 
    }) 
    } 
} 
0

我喜歡使用這種

scroll(container, target) { 
    let scrollTo = target.getBoundingClientRect().top; 

    $(container).animate({ 
     scrollTop: `+=${scrollTo}` 
    }, 900); 
} 

然後在HTML這樣做

<div #container> <!-- Scrolling container --> 
    <button (click)="scroll(container, intro)">Go To Intro</button> 
    <!-- other content --> 
    <div #intro></div> 
</div> 
0

我可以建議用戶NG2頁面滾動

ng2-page-scroll

安裝

npm install ng2-page-scroll --save 

進口在app.module.ts

import {Ng2PageScrollModule} from 'ng2-page-scroll'; 

@NgModule({ 
    imports: [ 
     /* Other imports here */ 
     Ng2PageScrollModule 
     ] 
}) 
export class AppModule { 
} 

測試它在你的HTML組件

<a pageScroll href="#test">Testing</a> 
<div id="test">