Angular: Custom Directive Using Selectors with IDs, Classes, and Attributes
In addition to using tag names and attributes, you can also create directive selectors that target HTML elements with specific IDs, classes, or data attributes.
Example: Highlighting Elements with Specific IDs, Classes, or Attributes
Let’s create a directive that highlights elements with the ID highlight-me
, the class highlight
, or the data attribute data-highlight="true"
:
@Directive({
selector: '#highlight-me, .highlight, [data-highlight="true"]',
standalone: true,
})
export class HighlightDirective {
private el = inject(ElementRef).nativeElement;
ngAfterViewInit() {
this.el.style.backgroundColor = 'yellow';
}
}
How it Works
The selector uses the following syntax:
#highlight-me
targets the element with the IDhighlight-me
.highlight
targets elements with the classhighlight
[data-highlight="true"]
targets elements with the data attributedata-highlight
set totrue
Example Template
Let’s see how this works in an example template:
<!-- Element with ID highlight-me -->
<div id="highlight-me">Highlighted by ID</div>
<!-- Element with class highlight -->
<div class="highlight">Highlighted by class</div>
<!-- Element with data attribute data-highlight="true" -->
<div data-highlight="true">Highlighted by data attribute</div>
<!-- Element without any of the above -->
<div>No highlight</div>
In this example, the first three elements will be highlighted because they match the selector. The fourth element will not be highlighted because it doesn’t match the selector.
Conclusion
In this post, we learned how to create directive selectors that target HTML elements with specific IDs, classes, or data attributes. This technique can be used to create more flexible and reusable directives in your Angular applications.