How to create custom directive in Angular?
In Angular, a custom directive is a way to extend HTML by creating your own custom HTML elements. Directives are attributes that you can add to your HTML elements to give them new functionality. Custom directives allow you to create reusable components that encapsulate the behavior and functionality you need in your application.
Custom directives can be created using Angular’s Directive API. They can be used to manipulate the DOM, apply styles, handle events, and more.
Here’s an example of how you could create a custom directive in Angular:
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
}
}
In the example above, we import the necessary Angular classes and then create a directive by using the @Directive
decorator. The selector
property in the decorator is the name of the directive, in this case appHighlight
. The directive class itself simply uses the renderer to set the background color of the element to yellow.
Once you have created a custom directive, you can use it in your HTML like this:
<p appHighlight>This text will be highlighted</p>
This is just a simple example of what you can do with custom directives in Angular, but they can be much more powerful and complex. They are an essential tool for creating scalable and maintainable applications in Angular.