2

In my app-routing.modules.ts I have the following script:

import { NgModule } from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {SearchComponent} from './search/search/search.component';
import {RegisterComponent} from './register/register.component';
import {LoginComponent} from './login/login.component';

const routes: Routes = [
  { path: 'search', component: SearchComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The HTML of my LoginComponent contains <a href="#">Top</a>. If the user clicks on that link, he will be redirected to the root page. I have also tried it with <a href="login/#">Top</a> but the same page will be reloaded.

What is the reason for that? I just want the user to jump on the top of the page.

xRay
  • 543
  • 1
  • 5
  • 29

4 Answers4

1

You can put a section that contains the top of your page with an ID like this:

<section id="top">
    <h1>Introduction</h1>
    <p>Top of the page </p>
</section>

Then in your link, you have to call the ID :

<a href="#top">Top</a>
ChillAndCode
  • 188
  • 2
  • 12
0

My problem was that I have used / after login (like login/#). My solution was using href="login#". I still don't understand why I need to add login, since it is the same page but that works.

xRay
  • 543
  • 1
  • 5
  • 29
0

From Angular 6.1, You can pass extraOptions to your RouterModule.forRoot() as a second parameter and can specify scrollPositionRestoration: enabled to tell Angular to scroll to the top whenever the route changes.

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled', // Add options right here
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Angular Official Docs

0

Instead of # use href="javascript:void". this should work

Raj
  • 385
  • 2
  • 15