Horizontal Scroll using buttons on angular2

后端 未结 2 1502
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 09:36

So I have this app in angular2 where I need to scroll a component horizontally but with buttons right and left. So I need a function for each button that scroll to right or

2条回答
  •  感情败类
    2020-12-29 09:50

    Import ViewChild and ElementRef to get elemenet refrence.

    use #localvariable as shown here,

    get element in component, @ViewChild('widgetsContent', { read: ElementRef }) public widgetsContent: ElementRef;

    change scrollvalue, this.widgetsContent.nativeElement.scrollTo({ left: (this.widgetsContent.nativeElement.scrollLeft + 150), behavior: 'smooth' });

    An example is shown below

    import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
    
    @Component({
        selector: 'my-app',
        template: `
                    
    WIDGET
    WIDGET
    WIDGET
    WIDGET
    WIDGET
    WIDGET
    `, styles: [` .info-widget { width: 31.75%; border: 1px solid black; display: inline-block; } .middle { float: left; width: 90%; overflow: auto; /*will change this to hidden later to deny scolling to user*/ white-space: nowrap; } `] }) export class AppComponent { @ViewChild('widgetsContent', { read: ElementRef }) public widgetsContent: ElementRef; public scrollRight(): void { this.widgetsContent.nativeElement.scrollTo({ left: (this.widgetsContent.nativeElement.scrollLeft + 150), behavior: 'smooth' }); } public scrollLeft(): void { this.widgetsContent.nativeElement.scrollTo({ left: (this.widgetsContent.nativeElement.scrollLeft - 150), behavior: 'smooth' }); } }

提交回复
热议问题