0

In my Angular4 app, when I'm scrolling down some list and click a list item to see details which is on another route, needs to scroll up to go to top of the page.

I have found some answers to set the scroll to top using JQuery. But is it possible to set the scroll to top using CSS(SASS may be) only?

ONE_FE
  • 968
  • 3
  • 19
  • 39

2 Answers2

1

try this, without any css. In your app component(bootstrap) subscribe the router and check event is a instance of NavigationEnd and then scoll window to top

import {Component, ElementRef, Inject} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
elementRef: ElementRef;

constructor(@Inject(ElementRef) elementRef: ElementRef,
          private router: Router) {
this.elementRef = elementRef;
router.events.subscribe((myEvent) => {
  if (myEvent instanceof NavigationEnd) {
    window.scrollTo(0, 0);
  }
 });
}
}

Here is working plunker : https://plnkr.co/edit/IyO1Cp?p=preview

Ankur Garg
  • 577
  • 3
  • 9
0

Here is quick example using css based smooth scrolling only. And here is another SO thread with more answers.

Hope this helps.

html {
  scroll-behavior: smooth
}

a {
  display: block;
  background: #fff;
  padding: 4px;
}

div {
  height: 1000px;
  width: 200px;
  padding: 4px;
}

#red {
  background: red;
}

#blue {
  background: blue;
}

#green {
  background: green;
}

#yellow {
  background: yellow;
}
<a name="top"></a>

<a href="#red">Red</a>
<a href="#blue">Blue</a>
<a href="#green">Green</a>
<a href="#yellow">Yellow</a>

<div id="red"><a href="#top">Top</a></div>
<div id="blue"><a href="#top">Top</a></div>
<div id="green"><a href="#top">Top</a></div>
<div id="yellow"><a href="#top">Top</a></div>
Geek
  • 2,766
  • 1
  • 19
  • 16