0

I have a component that uses an observable and it calls a service to make an API call. The API returns some HTML, which is rendered in the view.

The HTML looks something like this:

<p>abc</p><a href=\"http://abc.xyz.com/\" class=\"external-link\" rel=\"nofollow\">
Click me to open in new window</a>

In Angular, is there a way to add some JS, such that anchors with "external-link" class open in a new window or tab?

Jake
  • 25,479
  • 31
  • 107
  • 168
  • Would `target=\"_blank\"` not suffice? I wonder if perhaps you can implement something like the accepted answer here --> https://stackoverflow.com/questions/41609937/how-to-bind-event-listener-for-rendered-elements-in-angular-2, adding an event listener on clicking `...querySelector('external-link')` to navigate to the link in a new tab. Really not sure if the component will be able to bind html rendered from an observable, though. – Nathan Beck Feb 11 '19 at 20:48

1 Answers1

1

If the external links appear somewhere in your component templates, you could simply create a directive to target them:

@Directive({
  selector: '.external-link'
})

But it sounds like the HTML is being dynamically inserted here. In that case, Angular won't be able to compile the HTML to apply the directive.

You could take advantage of event delegation and catch the click event on some parent component. You can catch any click events to external links and add target="_blank":

@HostListener('click', ['$event'])
onClick({ target }) {
  if (target.classList.contains('external-link')) {
    target.setAttribute('target', '_blank');
  }
}

StackBlitz example.

Alex K
  • 1,937
  • 11
  • 12