Scroll to element on click in Angular 4

后端 未结 12 979
逝去的感伤
逝去的感伤 2020-11-29 18:57

I want to be able to scroll to a target when a button is pressed. I was thinking something like this.

相关标签:
12条回答
  • 2020-11-29 19:23

    In Angular you can use ViewChild and ElementRef: give your HTML element a ref

    <div #myDiv > 
    

    and inside your component:

    import { ViewChild, ElementRef } from '@angular/core';
    @ViewChild('myDiv') myDivRef: ElementRef;
    

    you can use this.myDivRef.nativeElement to get to your element

    0 讨论(0)
  • 2020-11-29 19:23

    You can do this by using jquery :

    ts code :

        scrollTOElement = (element, offsetParam?, speedParam?) => {
        const toElement = $(element);
        const focusElement = $(element);
        const offset = offsetParam * 1 || 200;
        const speed = speedParam * 1 || 500;
        $('html, body').animate({
          scrollTop: toElement.offset().top + offset
        }, speed);
        if (focusElement) {
          $(focusElement).focus();
        }
      }
    

    html code :

    <button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>
    

    Apply this on elements you want to scroll :

    <div id="elementTo">some content</div>
    

    Here is a stackblitz sample.

    0 讨论(0)
  • 2020-11-29 19:29

    You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.

    On the view(html file)

    <div id="target"> </div>
    <button (click)="scroll()">Button</button>
     
    
      
    

    on the .ts file,

    scroll() {
       document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
    
    0 讨论(0)
  • 2020-11-29 19:30

    I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.

    0 讨论(0)
  • 2020-11-29 19:33

    You can achieve that by using the reference to an angular DOM element as follows:

    Here is the example in stackblitz

    the component template:

    <div class="other-content">
          Other content
          <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
            Click to scroll
          </button>
        </div>
        <div id="content" #element>
          Some text to scroll
    </div>
    
    0 讨论(0)
  • 2020-11-29 19:35

    I need to do this trick, maybe because I use a custom HTML element. If I do not do this, target in onItemAmounterClick won't have the scrollIntoView method

    .html

    <div *ngFor"...">
          <my-component #target (click)="clicked(target)"></my-component>
    </div>
    

    .ts

    onItemAmounterClick(target){
      target.__ngContext__[0].scrollIntoView({behavior: 'smooth'});
    }
    
    0 讨论(0)
提交回复
热议问题