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

Getting and passing data from a frontend form to Java, then displaying it back in the frontend through Angular

The successful implementation of a payment verification SOAP XML API in JAVA has been achieved. Through the use of JAVA code, XML requests are sent to a payment API with SOAPAction headers and Body, resulting in a response from the API. Now, the goal is t ...

What is the best method to reset values in ngx-bootstrap date picker?

At the moment, it is only accepting the most recently selected values. To see a live demo, click here. ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

An issue occurred during the hydration process, causing the entire root to switch to client rendering since the error occurred outside of a Suspense boundary

I've started seeing some errors and warnings: Error: An error occurred while hydrating. Since it happened outside of a Suspense boundary, the entire root will switch to client rendering. Error: Hydration failed due to initial UI not matching what was ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

Encountering a Next.js TypeScript Build Error related to the Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' issue

`I am currently working on a project in Next Js using TypeScript. During the build process with npm run build, I encountered the following errors in the terminal: # Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' do ...

jQuery fails to operate on products loaded through AJAX requests

Upon opening the page, jQuery functions correctly. However, when a product is loaded or changed via AJAX, jQuery stops working. I am currently using jquery-1.7.1.min.js $(document).ready(function () { $screensize = $(window).width(); if ($screensi ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

What is the best way to dynamically render classes based on conditions in a table using React Bootstrap?

I am looking for a way to dynamically change the color of a class based on the transaction data in a table. import React from "react"; import Table from "react-bootstrap/Table"; import "./TableComponent.css"; const TableComponent = ({ Movement }) =&g ...

Utilizing Google OAuth2 API within an Angular2 Typescript Application

Looking to incorporate the Google oauth2 API and Calender API into my Angular2 application. Struggling to find a working sample to guide me through the integration process. Has anyone come across a functioning example? Thanks, Hacki ...

What is the process for sending an InMemoryUploadedFile to my S3 storage?

My upload form is quite simple and includes an image as a FileField: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): inst ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

What is the process for displaying the current bitcoin price on an HTML page using API integration?

I'm looking to develop an application that can display the current Bitcoin price by fetching data from the API at . I want to showcase this information within an h2 element. Any suggestions on how I could achieve this? Thank you in advance. const e ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

Having an issue with the 'scroll' event not being disabled in jQuery

Currently, we are encountering an issue with the implementation of a simple hiding menu when scrolling and showing it back once the user stops scrolling. The method .on('scroll') works as expected, but .off('scroll') is not functioning ...

Trouble with Jest when trying to use route alias in Next.js with Typescript

Currently, I am developing a Next.js App (v13.2.3) using Typescript and have set up a path alias in the tsconfig.json. Does anyone know how I can configure the jest environment to recognize this path alias? // tsconfig.json { "compilerOptions": ...

I'm encountering an issue with this error message: "Warning: Each item in a list must be assigned a unique 'key' prop."

I encountered an error message... Warning: Each child in a list should have a unique "key" prop. I'm puzzled about this because I believe I have assigned a unique key for my map. All the resources I've checked regarding this warning are relat ...

Is there a way to display incoming chat messages on the chat box without requiring a page refresh using socket.io?

Having trouble resolving an issue with my application hosted on wpengine, built using WordPress, vue.js, and socket.io for chat functionality. The main concern is that new messages posted in the chatbox do not display until the page is refreshed. I'm ...