how to move div scroll position based on button click in angular 2

前端 未结 2 402
星月不相逢
星月不相逢 2021-01-05 08:40

in app.component.html file i have one div element with horizontal scroll and two buttons as Next and Previous. based on these button click i want to move scroll.

相关标签:
2条回答
  • 2021-01-05 09:22

    I would prefer to use scrollIntoView() method. This method provides smooth scrolling transition effect in the browser when we click on the corresponding element.

        @Component({
        selector: 'my-app',
        template: `
          <div #panel class="some-class">
            <div *ngFor="let log of arr; let i = index" innerHTML="{{log}}" [id]="i"></div>
          </div>
          <button (click)="moveToSpecificView()">Move</button>
        `
    })
    export class AppComponent {
        public arr = ['foo', 'bar', 'baz'];
        @ViewChild('panel') public panel:ElementRef;
    
        public moveToSpecificView()(): void {
            setTimeout(() => {
                this.panel.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
            });
        }
    
      }
    
    0 讨论(0)
  • 2021-01-05 09:23

    This is how you scroll the div element - https://plnkr.co/edit/2v0iVgkOZfISqlFAkrNX?p=preview

    example:

    import { Component, ViewChild, ElementRef } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: `
        <div #panel style="overflow-y:scroll; height: 20px;" >
          <div *ngFor="let log of arr; let i = index" innerHTML="{{log}}" [id]="i"></div>
        </div>
        <button (click)="onPreviousSearchPosition()">Previous</button>
        <button (click)="onNextSearchPosition()">Next</button>
      `
    })
    export class AppComponent { 
      public arr = ['foo', 'bar', 'baz'];
      @ViewChild('panel', { read: ElementRef }) public panel: ElementRef<any>;
    
      public onPreviousSearchPosition(): void {
        this.panel.nativeElement.scrollTop -= 20;
      }
    
      public onNextSearchPosition(): void {
        this.panel.nativeElement.scrollTop += 20;
      }
    }
    
    0 讨论(0)
提交回复
热议问题