I am currently working on an Angular 8 application.
In this application, there is a specific requirement for handling links. For external links, such as www.ad.nl, clicking on them should open in a new tab.
However, if the link belongs to the same domain as the website (e.g., localhost: http://localhost:4200/gezondheid/Measurement/actieindex), it should load in the same tab instead of opening a new one.
To achieve this functionality, I have created a function for external links:
@Input() activities: Activity[];
isExternalLink(link: string): boolean {
const currentHost = window.location.hostname;
const linkHost = link.replace(/^http?:\/\/([^\/]*)\/.*/, (match, g1) => g1);
return currentHost !== linkHost;
}
getRouterLink(link: string): string {
return '/' + link;
}
Below is the template code that implements this logic:
<a
*ngIf="activity.link; else nolink"
[href]="activity.link"
[attr.target]="isExternalLink(activity.link) ? '_blank' : null"
[attr.rel]="isExternalLink(activity.link) ? 'noopener noreferrer' : null"
>
Currently, the issue arises when a link from the same domain is clicked, like http://localhost:4200/gezondheid/Measurement/actieindex, as it opens in a separate tab.