2017-04-26 49 views
0

我想從一個頁面導航到另一個頁面,並直接跳轉到目標頁面中間的一個控件。通常情況下,我們可以使用標籤「#」跟隨控件的名稱或ID。Angular 2:在加載頁面時跳轉到頁面的某個元素

但是,這種方法確實在Angular 2中工作得很好。我嘗試過像 Angular2 Routing with Hashtag to page anchor這樣的方法。用這種方法,網址以「#myId」結尾,但頁面實際上並沒有跳轉。

我們有其他方法來實現這個嗎?

回答

-1

Angular文檔項目具有AutoScrollService服務。你可以嘗試使用它。 auto-scroll.service.ts

/** 
* 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(/^#/, ''); 
    } 
}