简体   繁体   English

Angular 5-在新窗口中打开带有CSS类的链接

[英]Angular 5 - Open links with a CSS class in new window

I have a component that uses an observable and it calls a service to make an API call. 我有一个使用可观察对象的组件,它调用服务进行API调用。 The API returns some HTML, which is rendered in the view. API返回一些HTML,这些HTML在视图中呈现。

The HTML looks something like this: HTML看起来像这样:

<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? 在Angular中,是否可以添加一些JS,以便在新窗口或标签中打开带有“ external-link”类的锚点?

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. 但这听起来好像HTML是动态插入此处的。 In that case, Angular won't be able to compile the HTML to apply the directive. 在这种情况下,Angular将无法编译HTML以应用指令。

You could take advantage of event delegation and catch the click event on some parent component. 您可以利用事件委托并在某些父组件上捕获click事件。 You can catch any click events to external links and add target="_blank" : 您可以捕获到外部链接的任何点击事件,并添加target="_blank"

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

StackBlitz example. StackBlitz示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM