Angular: Mastering Directive Selectors

Abhishek Wadalkar
2 min readSep 8, 2024

--

Directive selectors are a powerful tool in Angular that allow you to automatically assign directives or limit the HTML elements that can use a directive. In this post, we will explore how to use directive selectors to make your custom directives even more powerful.

Automatic Directive Assignment

Let’s take our custom btLibsUiHighlight directive and change the selector so that it will be applied to all span elements by default:

TypeScript

selector: 'span, [btLibsUiHighlight]',

With this selector, the directive will automatically be applied to all span elements, and you can add it to other elements using the btLibsUiHighlight selector.

Opting Out

Now, let’s say you need an option to exclude some span elements. You can add the :not syntax to the selector like this:

TypeScript

selector: 'span:not([noHighlight]), [btLibsUiHighlight]',

Now, all span elements will have the highlight directive applied unless you add noHighlight to a span element.

Excluding HTML Elements

You can also exclude HTML elements using the :not syntax like this:

TypeScript

selector: '[btLibsUiHighlight]:not(label)',

With this selector, you can add the btLibsUiHighlight directive to all elements but the label element.

Selectors with IDs, Classes, and Attributes

You can also make selectors that apply directives to HTML elements with a specific ID, data attribute, or CSS class applied to the HTML element. Here is an example for all three options:

TypeScript

selector: '#someId, .someCssClass, [data-highlight="true"]'

Conclusion

In this post, we learned how to use directive selectors to make our custom directives even more powerful. By mastering directive selectors, you can automatically assign directives or limit the HTML elements that can use a directive. This opens up a world of possibilities for creating reusable and flexible 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