4

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your detailed answer. Is there any way to prevent adding slash in config level? Because I have to work on more pages nearly 25+ if I do it in html. Also User will access http://www.example.com#customer from different page. In that case, click event wont work.
If you want to use the same anchor from different pages then place the <div id=customer></div> in the current page and dynamically navigate there. Ex: this.router.navigate(['/path'], {fragment: "customer"}); This will scroll to anchor. Is this answer for your question? Fragment documentation: angular.io/guide/router#fragment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.