Scroll to a certain element of the current page in Angular 4

前端 未结 3 512
独厮守ぢ
独厮守ぢ 2020-12-19 06:16

Upon clicking a button (which is bottom of the page), I want to go to a certain element (in my case, #navbar) which is in the top of the current page, but I don\'t know how

相关标签:
3条回答
  • 2020-12-19 06:39

    I know, you want to scroll to a specific element in the page. But, if the element is in the top of the page, then you can use the following:

    window.scrollTo(0, 0);
    
    0 讨论(0)
  • 2020-12-19 06:47

    I think your way didn't work because of the empty router.

    this.router.navigate(['/home'], { fragment: 'top' });
    

    would work if 'home' is declared as a route and you have the id="top" element on it.

    I know you would like it to be "pure Angular way", but this should work (at least):

    gotoTop(){
      location.hash = "#navbar";
    }
    
    0 讨论(0)
  • 2020-12-19 06:56

    You can do this with javascript:

    gotoTop() {
      let el = document.getElementById('navbar');
      el.scrollTop = el.scrollHeight;
    }
    

    This will bring the DOM element with id="navbar" into view when the method is called. There's also the option of using Element.scrollIntoView. This can provide a smooth animation and looks nice, but isn't supported on older browsers.

    If the element is in a different component you can reference it several different ways as seen in this question.

    The easiest method for your case would likely be:

    import { ElementRef } from '@angular/core'; // at the top of component.ts
    
    constructor(myElement: ElementRef) { ... } // in your export class MyComponent block
    

    and finally

    gotoTop() {
      let el = this.myElement.nativeElement.querySelector('nav');
      el.scrollIntoView();
    }
    

    Working plunker.

    0 讨论(0)
提交回复
热议问题