2017-04-26 82 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(/^#/, ''); 
    } 
}