A lot of times it’s quite difficult to decide between what to use for href attribute while developing Angular 2+ applications. Following are 3 ways to do that:
1. href = “#”
This is considered the safest way to create a link without allowing the user to redirect anywhere on the link click.
But this method only works for HTML pages. In case of Angular, the page redirects to the base page.
2. href = “javascript:”
Using href=”javascript:” or javascript:void(0) violates the Content Security Policy as it can expose the page for certain types of attacks including Cross Site Scripting and data injection attacks.
So this is not advisable to use this on pages.
3. [routerLink]=””
Rather than using the href, using the routerLink is perhaps the best way to use in Angular. The routerLink attribute can be bound to a blank string using property binding. This will make sure that the value is always set to the route that the view is present in.
This has multiple benefits of using the Angular router to redirect pages. Second, staying on the same page will make sure that the page doesn’t refresh. Third, no need for adding custom styles to those <a> tags to make it look and behave like anchor tags.
If you know of any other to do the same, please let us know in the comments and I will make sure to add this up in the list.