Categories
Angular Answers

How to add routing with hashtag to page anchor with Angular?

Spread the love

Sometimes, we want to add routing with hashtag to page anchor with Angular.

In this article, we’ll look at how to add routing with hashtag to page anchor with Angular.

How to add routing with hashtag to page anchor with Angular?

To add routing with hashtag to page anchor with Angular, we can get the hash value and call scrollIntoView to scroll to the element with the given hash value as the ID.

For instance, we write

<a [routerLink]="['somepath']" fragment="Test">go to test</a>

in a template or

this._router.navigate(["/somepath", id], { fragment: "test" });

to navigate to /somepath.

The fragment property or attribute is set to the hash value.

Then in the destination component, we write

import { ActivatedRoute } from "@angular/router";

export class SearchComponent implements OnInit, AfterViewInit {
  //...
  private fragment: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.fragment.subscribe((fragment) => {
      this.fragment = fragment;
    });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector("#" + this.fragment).scrollIntoView();
    } catch (e) {}
  }
}

to call document.querySelector("#" + this.fragment).scrollIntoView(); in ngAfterViewInit to scroll to the item with the ID equal to this.fragment.

We watch for hash value changes with

this.route.fragment.subscribe((fragment) => {
  this.fragment = fragment;
});

Conclusion

To add routing with hashtag to page anchor with Angular, we can get the hash value and call scrollIntoView to scroll to the element with the given hash value as the ID.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *