Steps to create Custom Directives
Step 1: Create a Directive
ng generate directive <directive-name>
The above command helps us to create new directive.
Step 2: Implement necessary imports
Open the generated directive file and import necessary modules like ElementRef , HostListener etc.
ElementRef : Provides access to the respective DOM element to change the styles or properties .
HostListener : Decorator used to listen for events on the host element such as mouse controls , clicks etc.
Input (optional) : Allows you to pass data from the component template to the directive.
import {Directive, ElementRef, HostListener , Input } from '@angular/core';
Step 3: Define the Selector
In the @Directive decorator , we need to provide the `selector` property to specify how the directive will be used in the template. If we use the ng generate directive command, it gives selector property by default, we can also change this selector name for our usage.
@Directive({
selector: '[appHighlight]'
}
Step 4: Implement the logic
Here, we can write our custom functionality in the directive file. We can also implement life cycle hook methods in the directive file if required. Here we can also pass inputs to the directive using @Input decorator.
Step 5: Using our directive in template
In our component’s template, we can use the selector given in the directive as an attribute to the required element on which we want to perform our logic.
<element appNewDirective>.....content </element>
Here appNewDirective is the selector of our directive. In this way we can use the directive in our component templates with the custom functionality.
As mentioned above, we can also pass inputs to directive.
<element appNewDirective [input1]="value">.....content </element>
In this way we can pass inputs to our custom directive, here input1 is the input we declared as @Input() in our decorative, and `value` is the data we are passing to that particular input. Based on our requirement we can pass multiple inputs .
Attribute Directives in Angular
Attribute directives are a powerful tool that allows you to manipulate the behavior and appearance of HTML elements. In this article, you will see the fundamentals of attribute directives.
Table of Content
- What are Attribute Directive?
- Benefits of Attribute Directive
- Types of Attribute Directives
- Steps to create Custom Directives
- Example of Attribute Directives