0

I am working with scroll and try to initiate it at specific element by a given id.

my html looks like:

<div class="list-wrapper" style="max-height:350px;overflow-y:scroll" >
   <div *ngFor="let el of elements">
     <div class="text-center" id="element_{{el.id}}"
        {{el.lebel}}
     </div>
   </div>
 </div>

in my component

Future ngOnInit() async{
    await _apiService.getElements().then((resp){
    list = resp;
 });
 scrollToLastElement();
}

my scrollToLastElement method

void scrollToLastElement(){
    var wrapper = querySelector('.list-wrapper');
    Timer.run(() => wrapper?.scrollTop = wrapper?.scrollHeight);
}

but scroll always point at the first one. any suggestions ?

eftikhar
  • 119
  • 9
  • Check this thread - https://stackoverflow.com/questions/43916827/how-to-move-div-scroll-position-based-on-button-click-in-angular-2/47713811#47713811 – Praveen M P Mar 05 '18 at 07:20

3 Answers3

0

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Reference: How to get scrollbar position with Javascript?

ahmednawazbutt
  • 823
  • 12
  • 34
  • thank you, each time I print wrapper.scrollTop is always set to 0 before and after `Timer.run(() => wrapper?.scrollTop = wrapper?.scrollHeight);` it seems that the wrapper div is not available when I call `scrollToLastElement()` – eftikhar Mar 05 '18 at 07:02
  • what does inspect element says? – ahmednawazbutt Mar 05 '18 at 07:18
  • inspect element in the browser?, I can see the elements. my point is to call this method directly after the for is finish binding the data to the dom. – eftikhar Mar 05 '18 at 08:01
0

using

new Future.delayed(const Duration(seconds:1), () {});

instead of Timer.run((){}); will solve it.

thank you all.

eftikhar
  • 119
  • 9
0

I think you need:

Future ngOnInit() async{
    await _apiService.getElements().then((resp){
    list = resp;
    scrollToLastElement();
    });
}

This should work without changes to the scroll function as in your solution, which executes the scroll function after 1 second. One second will usually be enough for apiService to respond. But if it takes longer, your scroll won't work as the elements won't have been populated by then.

Dhruv Murarka
  • 376
  • 5
  • 12