Read this article at Devto WebsiteFew of below content does not render properly so instead of reading here, you can read this in Devto instead.

Secure your apps with Angular Directive when using target='_blank'


Hi, today I want to share with you guys on how to secure your apps if you are using target='_blank'.

Usually to link an external url, we will do something like this: <a href=''></a>.Please noted that this will still work. But unfortunately there is an security issues here.You can read more about it here and it also included with example:

To solve this issue we can simply add an extra attribute to anchor tag. <a href='' rel='noopener noreferrer'></a>.

However, let say in our app we have a lot of external link to put. And personally, I dont really like to write rel='noopener noreferrer' to every anchor tag I have.

With that, we can automatically add rel='noopener noreferrer' to every anchor tag with Angular Directive.

// target-blank.directive.ts

import { Directive, HostBinding } from '@angular/core';

  // target every <a target="_blank">...<a>
  selector: 'a[target=_blank]',
export class TargetBlankDirective {
  // will add <a ... rel='noopener noreferrer'>...</a>
  @HostBinding('attr.rel') rel = 'noopener noreferrer';
// and just use it like this
<a href='someurl' target='_blank'>someurl</a>

// will render like this
<a href='someurl' target='_blank' rel='noopener noreferrer'>someurl</a>

One last thing, let say you have dynamic action on click. How would we want to prevent this.

function openInNewTab(url: string): void {
    // open link in new tab
    const newTab =, '_blank')

    // set opener to null so that no one can references it
    newTab.opener = null


You can play around here stackblitz angular-target-blank

In conclusion:

Pro Cons
Automatically add rel='noopener noreferrer' New Developer unaware of this directive behaviour
Able to prevent this issue automatically Client disable JS

You can read more here