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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.