Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make scroll element into viewport in Angular 2+?

This is an example

There is the component with items list in it:

class HomeComponent {
    text = 'foo';
    testObject = {fieldFirst:'foo'};
    itemList = [
        '1', 
        '2', 
        '3', 
        '4',
        '5',
        '6',
        '7',
        '8 This one should be scrolled into viewport',
        '9',
        '10',
        '11',
        '12',
      ];

    scrollToElement() {
        // Do scroll there
    }
}

It's template:

 <button (click)="scrollToElement()">Scroll To 8th Element</button>
 <div class="wrapper">
    <li *ngFor="let item of itemList">{{item}}</li>
 </div>

And the styles:

.wrapper {
    max-height: 300px;
    overflow-y: scroll;
}

How to make scroll 8th element into viewport of "wrapper" div?

Update

This answer doesn't solve the problem because the question is not how to get element focused, the question is how to scroll to it.

like image 699
mr_blond Avatar asked Oct 16 '25 06:10

mr_blond


1 Answers

You can add a unique id to your list elements like this:

<li *ngFor="let item of itemList; let i = index;" id="list-item-{{i}}">{{item}}</li>

And then you can find the element in the click method, and use a method called, scrollIntoView(); like this.

scrollToElement() {
    document.getElementById("list-item-7").scrollIntoView();
}

Demo

like image 160
John Avatar answered Oct 18 '25 22:10

John