1

I used this jQuery code and it is working fine. But I want to use the same flow in angular. Is it possible? Can we write for beforeunload function in angular?

$(window).on('beforeunload', function(){
            $(window).scrollTop(0);
          });
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
kanakaraju
  • 11
  • 2

4 Answers4

0

You can do something like:

 ngOnInit(): void {
    document.body.scrollTop = 0;
    // or window.scrollTo(0, 0);
}
Ketan Akbari
  • 10,837
  • 5
  • 31
  • 51
  • I need whenever reload the page, then show the page is top by using of angular. Is it possible to write the code in angular? – kanakaraju Apr 02 '18 at 06:53
0

Yes, you can do this like-

<div (window:beforeunload)="someMethod()"></div>

Or You do like this-

@Component({ 
  selector: 'test',
  'template': ''
)}
class TestComponent {
  @HostListener('window:beforeunload')
  someMethod() {
    // You can handle scroll here
  }
}
deen
  • 2,185
  • 7
  • 29
  • 53
0

You can learn about Angular - Lifecycle Hooks

or mayble this link explaining the lifecycle methods.

ngOnInit() {
   window.scrollTo(0, 0)
}

You can also see this stackoverflow post about your problem. Cheers

Combine
  • 3,894
  • 2
  • 27
  • 30
0

try this html.

<div #list [scrollTop]="list.scrollHeight"></div>

In Component define id into html id="scrollId"

const element = document.querySelector('#scrollId');
element.scrollIntoView();

or

you can use this in TS

 window.scrollTo(0 , 0);

 window.scrollTo( 0 , document.body.scrollHeight);// where you can describe the height to scroll to
Abhishek Ekaanth
  • 2,511
  • 2
  • 19
  • 40
  • I need whenever reload the page, then show the page is top by using of angular. Is it possible to write the code in angular? – kanakaraju Apr 02 '18 at 06:53
  • i did not understand what you're trying to say – Abhishek Ekaanth Apr 02 '18 at 06:54
  • Hi Abhushek, thanks for the response. My intention is when I am scrolling down a page from top to bottom, say I reached bottom of the page and I clicked/reloaded the page right now as per browser behavior the page points to bottom . But I want to go to top of the page when page gets reloaded. – kanakaraju Apr 02 '18 at 06:59
  • Is it possible to achieve using angular 4.0? – kanakaraju Apr 02 '18 at 07:00
  • @kanakaraju by default when the page is reloaded it will point towards top of the page all the time and for every instance. – Abhishek Ekaanth Apr 02 '18 at 07:13