angular - 如何导航到 Angular 7 中的 anchor

标签 angular anchor routerlink

我已经在routingModule和所有路径中启用了anchorScrolling,但是当我单击链接时没有任何反应。

'nav-bar.component.html'

<div id="mySidenav" class="sidenav" #sidenav>
   <a href="javascript:void(0)" class="closeBtn" 
   (click)="closeNav()">&times;</a>
   <a routerLink="/hazyMinds" [fragment]="'HazyMinds'">HazyMinds</a>
   <a routerLink="/ourGames" [fragment]="'Games'">Our Games</a>
   <a routerLink="/contact" [fragment]="'Contact'">Contact</a>
</div>
<span id="openNavBtn"  (click)="openNav()" #openBtn>&#9776;</span>



'app.component.html'

<app-nav-bar></app-nav-bar>
<app-hazy-minds id="HazyMinds"></app-hazy-minds>
<app-games id="Games" ></app-games>
<app-contact id="Contact"></app-contact>
<router-outlet></router-outlet>



“app-routing.module.ts”

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

import {ContactComponent} from './contact/contact.component';
import {GamesComponent} from './games/games.component';
import {HazyMindsComponent} from './hazy-minds/hazy-minds.component';

const routes: Routes = [
  {path: '', redirectTo: '/', pathMatch: 'full'},
  {path: 'hazyMinds', component : HazyMindsComponent},
  {path: 'ourGames', component : GamesComponent},
  {path: 'contact', component : ContactComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      anchorScrolling: 'enabled',
      scrollOffset: [0, 64]
    }),
    CommonModule
  ],
  exports: [
    RouterModule
  ]
})


export class AppRoutingModule { }

我希望当我点击链接时它会自动滚动到正确的 anchor 。
有人知道我的代码有什么问题吗?谢谢

最佳答案

您可以为此使用片段:

this.router.navigate(['/results'], { fragment: 'top' });

//

<h1 id="top">asdasd</h1>

https://angular.io/api/router/NavigationExtras

关于angular - 如何导航到 Angular 7 中的 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855195/

相关文章:

angular - 从 void 函数返回

angular - 如何在 Angular2 2.0.0 RC.5 中设置全局提供者?

javascript - 突出显示 anchor 的目标元素中的元素?

angular - 仅参数更改时,Angular 4 中的 routerLinkActive 不添加类

angular - 如何在 Reactjs 中制作类似 Angular 路由器导出?

javascript - jQuery 菜单事件链接

javascript - 使用 #anchor 重新加载页面而不发送发布数据

angular - 如何在 SVG 路径中使用 routerLink?

Angular 2 - routerLink 不适用于外部链接

Angular 2 : Binding dropdowns values with 'n' numbers