【问题标题】:Pages gets reloaded when the href attribute contains '#'当 href 属性包含“#”时,页面会重新加载
【发布时间】:2020-03-16 06:35:38
【问题描述】:

在我的 app-routing.modules.ts 我有以下脚本:

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 { }

我的 LoginComponent 的 HTML 包含 <a href="#">Top</a>。如果用户单击该链接,他将被重定向到根页面。我也用<a href="login/#">Top</a> 尝试过,但是会重新加载相同的页面。

这是什么原因?我只是想让用户跳到页面顶部。

【问题讨论】:

标签: html angular typescript


【解决方案1】:

您可以使用如下 ID 放置包含页面顶部的部分:

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

然后在您的链接中,您必须调用ID:

<a href="#top">Top</a>

【讨论】:

    【解决方案2】:

    我的问题是我在login 之后使用了/(如login/#)。我的解决方案是使用href="login#"。我仍然不明白为什么我需要添加login,因为它是同一个页面,但可以。

    【讨论】:

      【解决方案3】:

      从 Angular 6.1 开始,您可以将 extraOptions 作为第二个参数传递给您的 RouterModule.forRoot(),并且可以指定 scrollPositionRestoration: enabled 来告诉 Angular 在路径更改时滚动到顶部。

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

      Angular Official Docs

      【讨论】:

      • 我已经尝试过了,但它仍然会重定向到根页面。
      【解决方案4】:

      而不是 # 使用 href="javascript:void"。这应该工作

      【讨论】:

      • 而不是 href = "#" 在角度中使用 href = "javascript:void"
      猜你喜欢
      • 2016-03-06
      • 2012-08-21
      • 2021-09-10
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2017-11-29
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多