Angular 6 |路由器链接

Angular 6 | RouterLink

有什么方法可以在不重新加载的情况下转到另一个由 id 定义的页面部分

Angular v6.1 中添加了一系列新的滚动功能。

引用博客 post 中的一段话:

The Router Scroller provides functions related to scrolling to the Angular Router. With Router Scroller, you can do the following things.

Restore to scroll position before transition when browser back Fragmented URL like #foo and automatically scroll to elements with corresponding ID

我假设您要问的是第二段(锚点滚动)?

如果是这样,您可以在这里找到更多信息:

https://medium.com/lacolaco-blog/introduce-router-scroller-in-angular-v6-1-ef34278461e9

https://blog.ninja-squad.com/2018/07/26/what-is-new-angular-6.1/

你可以使用 scrollIntoView 方法

致谢 to:ibenjelloun

示例:https://stackblitz.com/edit/angular-scroll-spy-routing

@HostListener('scroll', ['$event'])
onScroll(event: any) {
    let currentSection: string;
    const children = this._el.nativeElement.children;
    const scrollTop = event.target.scrollTop;
    const parentOffset = event.target.offsetTop;
    for (let i = 0; i < children.length; i++) {
        const element = children[i];
        if (this.spiedTags.some(spiedTag => spiedTag === element.tagName)) {
            if ((element.offsetTop - parentOffset) <= scrollTop) {
                currentSection = element.id;
            }
        }
    }
    if (currentSection !== this.currentSection) {
        this.currentSection = currentSection;
        this.sectionChange.emit(this.currentSection);
    }
}