In normal circumstances, routing in Angular is done in one of the following ways:
[routerLink]="someDynamicUrl()"and Angular takes it from there.
Almost all routing scenarios can be realized by using one of the methods above. An example of a scenario which is not covered by the above: page content is rendered dynamically with contents loaded after the application has started, including hyperlinks to other pages on the same site. This is the scenario which www.bytethisstore.com was faced with. The sections below will outline our scenario and a reusable way in which we've implemented the solution.
A few texts on our website are defined external of the code repositories in a configuration repository. Since this is outside of the Angular codebase, we cannot include Angular directives, such as
routerLink. We also did not want to write some parser to try to determine when urls are present and manually attach listeners. We chose to format the texts as HTML, and when hyperlinks were needed, declare them as regular hyperlinks with the href attribute. However, if the user clicks on such a link, it will reload the entire page, even if the link points to a page on the same website.
In order to resolve the issue of page reloading, we have created an event listener to listen to click events and intercept events which are hyperlink clicks. A quick and easy way to implement is to use Angular's
The above example is easy to integrate; drop it into the root component and it will function. However, there are some valid reasons why HostListener should be avoided. A simple alternative is to attach an
event listener to the window object. The code below outlines the additional step of registering the event listener.
With any of the above implementations, your code will be able to route with 'href' attributes as if they were 'routerLink' attributes. Note: this takes advantage of how Angular adds attributes to anchor elements. This may be subject to change in future versions of angular.
Congrats, you made it to the end of the article! We think one of these articles below might be a good next step along your journey:
Feel free to check out some of our merch while you're here!
Thanks for reading! This page was last updated on 8/26/2021
Follow us on social media for updates and new dev pages and to help support our brand!
Fill out the form below and we'll send you an email reminder to visit this page again:
We've saved your reminder and will send you an email when the time comes.
Unfortunately, there was an error saving your reminder. Please try again.