Prevent adding slash before hash in Angular 7

Viewed 678

I want to add the hash in the URL to go to particular section. My code is to reach the customer section in that page

<a href="#customer">Customers</a>

When I click this link, the URL will be updated like below.

http://www.example.com#customer

But Angular 7 adds slash / before hash # in the URL after some fraction of seconds and URL will become like this.

http://www.example.com/#customer

But the page remains same even though its updating slash.

The issue is When I try to click the Cutomers link again, the URL will be http://www.example.com#customer

So URL mismatch will happen here as no slash will be there before hash when I click second time. so it reloads the page

How to prevent adding slash before hash in angular 7

1 Answers

By default the anchor scrolling is not enabled in Angular Router (after v.6.1.0).

You can enable it by importing RouterModule like this:

RouterModule.forRoot(routes, {
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled'
})

Doc: https://angular.io/api/router/ExtraOptions#anchorScrolling

Your anchor will be the id of the div.

Usage

HTML:

<a [routerLink]="['somepath']" fragment="customer">Jump to 'customer' anchor </a>

TS:

 this.route.fragment.subscribe(f => {
    console.log("f ", f);
    const element = document.querySelector("#" + f)
    if (element) element.scrollIntoView()
  });

Other solutions.

You can use dynamic scrolling.

<div #customer>Customers</div> <button (click)="scrollToElement(customer)">Scroll</button>.

And in your ts file:

scrollToElement(el) {
    el.scrollIntoView();
}

Or use ViewChild:

 @ViewChild("customer") customerElement: ElementRef;

this.customerElement.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });

Or use some angular librarie like: https://www.npmjs.com/package/@nicky-lenaers/ngx-scroll-to

Related