Angular: Using Directive Selectors to Automatically Assign Directives
Directive selectors are a powerful tool in Angular that allow you to automatically assign directives to HTML elements based on their tag…
Angular: Using Directive Selectors to Automatically Assign Directives
Directive selectors are a powerful tool in Angular that allow you to automatically assign directives to HTML elements based on their tag name, attributes, or classes. In this post, we will explore how to use directive selectors to automatically assign a custom directive to all span elements.
Example: Automatically Highlighting Span Elements
Let’s say we want to create a custom directive that highlights all span elements in our application. We can create a directive with the following selector:
@Directive({
selector: 'span, [highlight]',
standalone: true
})
export class HighlightDirective {
private el = inject(ElementRef).nativeElement;
ngAfterViewInit() {
this.el.style.backgroundColor = 'yellow';
}
}
In this example, just need to add HighlightDirectivein parent component import array ,then HighlightDirective will be automatically applied to all span elements in our application. The ngAfterViewInit lifecycle hook is used to set the background color of the span element to yellow.
How it Works
When Angular encounters a span element in the template, it will automatically apply the HighlightDirective to that element. This is because the directive selector matches the span tag name.
Using the Directive
To use the directive, simply add a span element to your template:
<span>Highlighted text</span>
The text inside the span element will be highlighted in yellow.
Conclusion
In this post, we learned how to use directive selectors to automatically assign a custom directive to all span elements in an Angular application. This technique can be used to create reusable and flexible directives that can be applied to multiple elements in your application.
메타데이터
- post_id
- 616fa3dba10e
- slug
- angular-using-directive-selectors-to-automatically-assign-directives-616fa3dba10e
- url
- https://medium.com/@abhishekw/angular-using-directive-selectors-to-automatically-assign-directives-616fa3dba10e
- canonical_url
- https://medium.com/@abhishekw/angular-using-directive-selectors-to-automatically-assign-directives-616fa3dba10e
- author_url
- https://medium.com/@abhishekw
- status
- ok
- fetched_at
- 2026-07-24 12:32:17