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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With