How to smooth scroll to page anchor in angular 4 w

2019-01-22 23:10发布

What I want to achieve is a click to and do a smooth scroll to bottom / specified div area which i define with hashtag just like i think it should be like this.

here is the live example in the w3school example which is written for JQuery: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll

What I do is peek from this answer: Angular2 Routing with Hashtag to page anchor

but i don't really understand the answer, the answer is looked like this :

this part is HTML part :

<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>

and below this, the router.navigate is where should I put the code? component.ts right? but how do i access this function? should i implement (click)?

this._router.navigate( ['/somepath', id ], {fragment: 'test'});

and below this, i get it, which it should write in my component.ts :

** Add Below code to your component to scroll**

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import

  private fragment: string;

  constructor(private route: ActivatedRoute { }

  ngOnInit() {
    this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) { }
  }

what is the "somepath" mean? I should add a route in my routes.ts right? usually, i add a new path in here for example like this :

export const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'product', redirectTo: '/product' },
  ...homeRoutes,
  ...productRoutes
];

can anyone provide me with full example code in HTML, routes, and component?

5条回答
欢心
2楼-- · 2019-01-22 23:25

Try removing the square brackets:

class="startScroll" scrollTo="'#firstDiv'" scrollBoxID="'#scrollBox'"
查看更多
乱世女痞
3楼-- · 2019-01-22 23:33

I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular (angular 6+) so decided to look into other option and found a solutionwhich use scrollIntoView and this seems to be the best solution so far

HTML code :

<button (click)="scrollToElement(target)"></button>
<div #target>Your target</div>

Ts code :

scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
查看更多
Explosion°爆炸
4楼-- · 2019-01-22 23:34

First of create directive of scroll

import { Directive, HostListener, Input, OnInit } from '@angular/core';
declare var $: any;

@Directive({
    selector: '[scrollTo]'
})
export class ScrollToDirective implements OnInit {

    @Input('scrollTo') scrollTo: string;
    @Input('scrollBoxID') scrollBoxID: string;

    constructor() { }

    ngOnInit(): void {

    }

    @HostListener('mousedown')
    onMouseClick() {
        var id = this.scrollTo;
        var scrollBoxID = this.scrollBoxID;
        var elementOffset = $(scrollBoxID).offset().top + 10;

        $(scrollBoxID).animate({
            scrollTop: $(scrollBoxID).scrollTop() + ($(id).offset().top - elementOffset)
        }, 1000);
    }
}

Here your html code

<li>
    <label class="startScroll" [scrollTo]="'#firstDiv'" [scrollBoxID]="'#scrollBox'"> First </label>
</li>
<li>
    <label class="startScroll" [scrollTo]="'#secondDiv'" [scrollBoxID]="'#scrollBox'"> Second </label>
</li>

<div id="scrollBox">
     <div class="first" id="firstDiv"></div>
     <div class="second" id="secondDiv"></div>
</div>
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-22 23:43

from what i read and what i search, it will be a hell of a code for just a SMOOTH SCROLL its not simply like JQuery i think, so i decided to use this plugins which is work perfectly : https://www.npmjs.com/package/@nicky-lenaers/ngx-scroll-to

feel free to use it

查看更多
Summer. ? 凉城
6楼-- · 2019-01-22 23:51

You can simply do this in your component.

const element = document.querySelector("#destination")
if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

查看更多
登录 后发表回答