What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this:

    <a [href]="getUrl()">click me</a>

    getUrl() {
      return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com');
    }

The link is not clickable. When hovering over the link, the URL is visible but the click event does not seem to work.

Whether using the sanitizer method or not, there doesn't seem to be any difference.

Edit:

Let me provide some additional context on what I am trying to achieve. I simply need to dynamically append some HTML. Initially, I tried this:

<div [innerHTML]="getHtml()"

getHtml() {
return this.domSanitizer.bypassSecurityTrustHtml(html);
}

However, when doing it this way, the links are broken and can only be opened with right-click menu. Without using bypassSecurityTrustHtml method, the links work but styling is mostly lost.

So far, I have also attempted:

for (const el of this.div.nativeElement.getElementsByTagName('a')) {
   // like this
   this.renderer.listen(el, 'click', () => {this.getUrl()});

  // or like this
   el.onclick = function (event) {
     window.open('http://testurl.com');
   };
}

But none of these methods seem to work.

What does work:

 // for some reason, links work with this
 changeDetection: ChangeDetectionStrategy.OnPush

Although this solution solves my problem, I am not fond of it:

 @HostListener('mouseup', ['$event'])
  onClick(event) {
    if(event.target && event.target.href) {
       window.open(event.target.href);
     }
  }

Answer №1

Below are the steps to make the necessary changes:

  1. In your HTML code, add the following line -

<a href="#" (click)="getUrl()">Click me</a>

  1. In your TypeScript file, follow these steps - -- Import DomSanitizer from platform-browser

import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';

Create an instance of Domsanitizer

constructor(private domSanitizer: DomSanitizer) {}

Invoke your method like this

getUrl() {
      return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com');
    }

Answer №2

After some trial and error, I came up with a solution that worked:

  @HostListener('mouseup', ['$event'])
  onClick(event) {
    if (event.target && (event.target.href || event.target.closest('a')) && event.target.closest('.notificationHtmlDiv')) {
      const a = event.target.href ? event.target : event.target.closest('a');
      let target = a.target ? a.target : '_self';
      if(event.button === 1) {
        target = '_blank';
      }
      window.open(a.href, target);
    }
  }

It appears that angular is preventing click events on SafeHtml content. For example, applying onclick to a div outside of dynamically added HTML worked fine, but the same approach for an <a> tag inside dynamically added HTML did not work at all.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify enum values within controller function

I am dealing with a query parameter in my REST API that should be restricted to specific values according to an enum type. I need to find a way to handle a "Bad Request" error if the client provides any value outside of this enum. Here is what my enum loo ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

The karma test encounters difficulties in establishing a connection with the 'chrome' instance that has been launched

Currently, I am facing an issue with my Karma test running on a nodejs jenkins pod. npm is timing out when trying to connect to the Chrome instance on the selenium hub. Everything was working fine until yesterday without any changes made to the configura ...

Enhance scrolling with a bounce effect

My goal is to implement a smooth scrolling experience with a bounce effect when the user over-scrolls, meaning they scroll too much to the top or bottom. I found an answer on Stack Overflow that explains how to achieve smooth scrolling, but I also want to ...

Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code: import * as mathFn from './formula/math'; export functi ...

Is it considered poor practice to specify the type explicitly when it can be easily inferred by Tslint?

When using VSCode, the linter tslint may raise an issue when the following code is added with a specific type: serverId: number = 10; This will trigger the following message: [tslint] Type number trivially inferred from a number literal, remove type ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

The getTotalLength() method in SVG may not provide an accurate size measurement when dealing with non-scaling-stroke. To obtain the correct scale of

In my current project, I am utilizing JavaScript to determine the length of a path and apply half of that length to the stroke-DashArray. However, I have encountered an issue as I am using vector-effect="non-scaling-stroke" in order to maintain a consisten ...

Utilize the Nextel API to send SMS messages with the sender's number clearly displayed in

Hello, I am currently utilizing the Vonage API to send SMS messages through my Node JS application. Although the receiver does successfully receive the message, it appears as though it is coming from an anonymous number. Is there a way to modify the "Fro ...

Guide to retrieving static information for forms with the use of reactive forms

I am encountering an issue with my reactive form. When I click the new button, a duplicate section appears but the options in the select field are not visible. Additionally, I receive errors as soon as the page loads: ERROR Error: Cannot find control with ...

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

Issues with Weglot link hooks not functioning properly within the sticky header

I have integrated Weglot for translations on my website, aigle.ca. Due to issues with their widget, I am using link hooks instead. You can find more information about link hooks at: weglot.com link-hooks However, when scrolling down the page and the menu ...

Phonegap experiencing issues with executing JavaScript code

My attempt to utilize phonegap is encountering an issue where my javascript is not running. Here's what I've tried so far: <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" / ...

Having issues extracting information from easports.com due to difficulties with the <ea-elements-loader> element

Recently, I've been developing a Python WebScraper to extract data (such as wins and losses) from our FIFA ProClub by crawling various websites. While I successfully implemented it on a third-party website using BeautifulSoup and requests, I encounter ...

Pointer Permissions parsing does not permit creation

Despite meticulously following the instructions in this guide, I am encountering a 403 error when attempting to create a new row: Error code: 119 Error message: "This user does not have permission to carry out the create operation on Messages. This s ...

Retrieve the output from PHP in JSON format and then utilize jQuery to parse it

I am currently working on a jQuery function $.post(file.php), where the data is being sent to "file.php" and returned in JSON format using json_encode(). Although I am able to successfully retrieve the result, I am unsure how to separate the individual i ...

Having trouble with my AJAX request and can't figure out why. Anyone available to take a look and help out?

I have successfully implemented this AJAX script on various pages in the past without any issues. <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script& ...

Does Material-UI MenuItem pass arguments to the onClick handler function?

I am currently working with a search.js file and a search-date.js file. Within the search.js file, there is a container called SearchDate which I render. However, I'm puzzled by the behavior of the MenuItem component when it is clicked. The function ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

Analyzing the DOM content loading time for web pages generated using AJAX technology

When analyzing website performance, I rely on window.performance.timing. However, this method falls short when it comes to measuring the performance of webpages loaded through ajax calls. For instance, websites built with frameworks like angularjs often lo ...