如何导航到Angular 7中的锚点 [英] How can I navigate to an anchor in Angular 7

查看:548
本文介绍了如何导航到Angular 7中的锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在routingModule和所有路径中启用了anchorScrolling,但是当我单击链接时,什么都没有发生.

I've enable the anchorScrolling in routingModule and all the path but when i click on links nothing happened.

'nav-bar.component.html'

'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.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'



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

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

I expect that when i clicked on link it automatically scroll to the correct anchor.
Someone know what's wrong with my code? thanks

推荐答案

您可以为此使用片段:

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

//

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

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

这篇关于如何导航到Angular 7中的锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆