Since the Angular release, we are used directive term and their uses in the application. they provided built-in directives but are going to see how to create our own directive?
Basically custom directive is the instruction given to DOM. where we can enhance the capability of HTML DOM.
There are three kinds of directives in Angular :
- Component: Directives with the template, It is the Most common Directive.
- Structural Directives: Change the DOM by adding and removing DOM elements, It changes the structure of directives eg. ngIf and ngFor
- Attribute Directives: Change the appearance or behaviour of an element, component or another directive.
Below are the steps to create custom directives —
- Create decorator with @Directive decorator
- import Directive, ElementRef dependencies
- Register directive in AppModule
Here we imported Directive and ElementRef from the angular core, Directive gives the functionality of @Directive decorator and inside that, we added selector name as appHighLight .
We also imported ElementRef which used to access the DOM elements.
After this, we need to add or register this directive in out app.module.ts
To use newly created Directives add it to HTML element.
Reacting to User Events
To make interactive host element like mouse hover, mouse click we need @HostBinding() and @HostBinding().
Below are steps to implement —
- Import HostListner
2. Add an event handler to response user
Here we added two events to mouse enters and mouse leaves by Hostlistner decorator, Host listener capture the event Host Element.
After running the app you will see the below result as background color changes when the mouse pointer is hover.
We can change the property of Host Element by @HostBinding-
@HostBinding(‘style.backgroundColor’) backgroundColor : string;
The passing value inside the directive
In the above example we can see color is hardcoded in ts file so here we can pass a value to this directives by using @Input decorator
This input can be passed using the below template-
<p appHighlight highlightColor=”yellow”>Highlighted in yellow</p>
I hope you like this post, please like and share!✌️