Scroll buttons in angular application

Discussão em 'Angular' iniciado por JudahA, Fevereiro 10, 2025.

  1. JudahA

    JudahA Guest

    [Sorry for my bad English]

    I have to create scrollable view, with scroll buttons, like this picture:

    [​IMG]

    Spec:

    • When the list is overflow, then show right/left buttons.
    • When there is not overflow, hide the scroll buttons.
    • When the scrollLeft === 0 then disable the left button. and also, when the scrollLeft value is max, then disable the right button.
    This is my try:

    Template:
    <section class="list-with-scroll">

    <div class="list" #list>
    <div *ngFor="let i of items" class="item">{{i}}</div>
    </div>

    <button class="scroller" *ngIf="isOverflown(list)" [class.disable]="!canScrollStart(list)" (click)="scroll(list,-1)" id="scroll-left">&#8678;</button>

    <button class="scroller" *ngIf="isOverflown(list)" [class.disable]="!canScrollEnd(list)" (click)="scroll(list,1)">&#8680;</button>
    </section>


    Component:

    export class AppComponent {
    items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"];

    isOverflown(element: HTMLElement) {
    return element.scrollWidth > element.clientWidth;
    }

    scroll(element: HTMLElement, direction: number) {
    element.scrollLeft += 100 * direction;
    }

    canScrollStart(element: HTMLElement) {
    return element.scrollLeft > 0;
    }

    canScrollEnd(element: HTMLElement) {
    return element.scrollLeft < element.scrollWidth;
    }
    }


    CSS:
    /* The rest of css see on staclblitz */

    #scroll-left{
    order: -1; /* To pevent ExpressionChangedAfterItHasBeenCheckedError */
    }


    StackBlitz: https://stackblitz.com/edit/my-angular-scroll

    The help I need:

    • I feel that my solution is very ugly.
    • When whe window/viewport resized, it doesn't update the state of buttons. I can listen to all events, but i don't know hou what is the best way do to it.
    • I don't know how to disable the right button when the scrollLeft value is max. Resolved. Thanks to @Void Spirit

    Thenk you for any help.

    Continue reading...

Compartilhe esta Página