Home > Software design >  Angular directive that doesn't match mailto
Angular directive that doesn't match mailto

Time:06-19

I'm trying to write a directive selector that matches any anchor tag with an href that isn't a mailto. I tried the following:

@Directive({
    selector: 'a[href]:not([href^="mailto:"])',
    standalone: true
})

but it's still matching the mailto links. How do I write it so that it doesn't match mailto?

CodePudding user response:

As @SurajRao mentioned that seems the^= symbol doesn't work in the Angular Directive selector, you may consider working with regex to check the HtmlArchorElement with the href starts with "mailto:".

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

@Directive({
  selector: 'a[href]',
  standalone: true,
})
export class ExcludeMailToDirective {
  readonly regex = new RegExp(/^mailto:/);

  constructor(el: ElementRef) {
    if (!this.regex.test(el.nativeElement.href))
      el.nativeElement.style.backgroundColor = 'pink';
  }
}

Sample StackBlitz Playground

  • Related