DEV Community


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

azrizhaziq profile image Azriz Jasni Updated on ・2 min read

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

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

Discussion (4)

Editor guide
jedi_zaidi profile image
Ahmad Zaidi • Edited

simple yet crucial! thanks for sharing!

if you're using vue, you can do this by simply creating component with rel="noopener norefferer" specified on the anchor tag.

mparpaillon profile image
Michel Parpaillon

I think you made a typo. You typed ref='noopener noreferrer' 3 times instead of "rel".

azrizhaziq profile image
Azriz Jasni Author

Thank man, appreciate your sharp 👀

bmitchinson profile image
Ben Mitchinson

Thanks for this!