Reputation: 1730
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.
Upvotes: 4
Views: 6345
Reputation: 16
In your element add in the CSS overflow: auto; this property add scroll in overflow-x and overflow-y.
Example
const $btn = document.getElementById("btn")
const $listItem = document.getElementById("element")
$btn.addEventListener("click", function() {
window.scrollTo(0, 4000)
// Here yo calculate the position of your element
})
.list {
overflow: auto;
max-height: 200px;
list-style-type: none
}
.list .list-item {
margin: 0 0 5px 0;
}
.button {
display: block;
width: 200px;
background: #e1e1e1;
color: black;
border-radius: 42px;
padding: 14px;
font-size: 16px;
cursor: pointer;
cursor: pointer
}
<button class="button" id="btn">Scroll to element</button>
<ul class="list">
<li class="list-item">Test 1</li>
<li class="list-item">Test 2</li>
<li class="list-item">Test 3</li>
<li class="list-item">Test 4</li>
<li class="list-item">Test 5</li>
<li class="list-item">Test 6</li>
<li class="list-item">Test 7</li>
<li class="list-item">Test 8</li>
<li class="list-item">Test 9</li>
<li class="list-item">Test 10</li>
<li class="list-item">Test 11</li>
<li class="list-item">Test 12</li>
<li class="list-item" id="element">Test 13</li>
<li class="list-item">Test 14</li>
</ul>
Upvotes: 0
Reputation: 11399
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();
}
Upvotes: 5