How can I navigate to an anchor in Angular 7

samy ben picture samy ben · Dec 19, 2018 · Viewed 9.8k times · Source

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

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

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

Answer

enno.void picture enno.void · Dec 19, 2018

You can use fragments for this:

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

//

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

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