Angular: Opting Out of a Directive with the :not Syntax

Abhishek Wadalkar
1 min readSep 8, 2024

--

In the previous post , we automatically applied the HighlightDirective to all span elements. However, what if we want to exclude certain span elements from being highlighted? We can use the :not syntax in our directive selector to achieve this.

Updated Directive Selector

Let’s update our directive selector to exclude span elements with the noHighlight attribute:

@Directive({
selector: 'span:not([noHighlight]), [highlight]',
standalone: true
})
export class HighlightDirective {
private el = inject(ElementRef).nativeElement;

ngAfterViewInit() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}

How it Works

The :not syntax in the selector tells Angular to exclude any span elements that have the noHighlight attribute. This means that only span elements without the noHighlight attribute will have the HighlightDirective applied.

Example Template

Let’s see how this works in an example template:

<!-- This span will be highlighted -->
<span>Highlighted text</span>

<!-- This span will not be highlighted -->
<span noHighlight>No highlight</span>

<!-- This element will also be highlighted -->
<div highlight>Highlighted div</div>

In this example, the first span element will be highlighted because it doesn't have the noHighlight attribute. The second span element will not be highlighted because it has the noHighlight attribute. The div element will also be highlighted because it has the highlight attribute.

Conclusion

In this post, we learned how to use the :not syntax in a directive selector to exclude certain elements from being affected by a directive. This technique can be used to create more flexible and reusable directives in your Angular applications.

--

--

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet