In this blog post, we will learn how to create a custom directive in Angular and provide a real-time scenario for beginners to understand how to use it.
First, let’s start with what a directive is. A directive in Angular is essentially a marker on a DOM element (such as an attribute, element name, or CSS class) that tells Angular to attach a specific behavior to that element or transform it in some way. Directives are a powerful feature of Angular that allow you to create reusable components, apply logic to elements, and modify the DOM in a declarative way.
Video tutorial
To create a custom directive in Angular, you’ll need to follow these steps:
Step 1: Create a new directive using the CLI
ng generate directive myDirective
This will create a new file called my-directive.directive.ts
in the src/app
folder.
Step 2: Implement the directive logic
Now that you have a new directive file, you can start implementing its logic. A directive is essentially a class with some metadata that tells Angular how to use it. Here’s an example of a simple directive that adds a red background color to an element:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirectiveDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
This directive uses the ElementRef
service to get a reference to the element it’s attached to and then sets its background color to red.
Step 3: Use the directive in your template
Now that you’ve defined your custom directive, you can use it in your templates like any other directive. Here’s an example of how you can use the myDirective
the directive we just created:
<div myDirective>Some text</div>
This will add the red background color to the div
element.
Angular custom directives – Real-time scenario for beginners :
Let’s say you want to create a custom directive that highlights all the links in your application that point to external websites. You can create a new directive called externalLink
that adds a small icon next to the link and changes its color to red:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: 'a[externalLink]'
})
export class ExternalLinkDirective {
constructor(private el: ElementRef) {
const link = el.nativeElement as HTMLAnchorElement;
if (link.host !== window.location.host) {
link.style.color = 'red';
link.innerHTML += ' <i class="fa fa-external-link"></i>';
}
}
}
This directive checks whether the link’s hostname is different from the current hostname (i.e., whether it points to an external website), and if so, it adds the icon and changes its color to red.
You can then use this directive in your templates like this:
<a href="https://www.google.com" externalLink>Google</a>
This will highlight the link to Google with a red color and an external link icon.
Another Custom Directive in a Real-Time Scenario
Let’s say you want to create a custom directive that changes the background color of an element when the user hovers over it. Here’s how you can do it:
- Create a new directive using the
@Directive
decorator:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
In this example, we’ve created a custom directive called HoverDirective
. It has a selector appHover
and uses the @HostListener
decorator to listen for mouseenter and mouseleave events on the element.
- Add the directive to your module’s
declarations
array:
import { NgModule } from '@angular/core';
import { HoverDirective } from './hover.directive';
@NgModule({
declarations: [
HoverDirective
]
})
export class AppModule { }
3. Use the directive in your component’s template:
<div appHover>Hover over me to see the effect</div>
In this example, we’ve added the appHover
directive to a div
element. When the user hovers over the element, the onMouseEnter
function is called, which sets the background color to “yellow”. When the user moves the mouse away from the element, the onMouseLeave
function is called, which sets the background color back to its original value.
This is just one example of how you can use a custom directive in a real-time scenario. The possibilities are endless – you can create custom directives for handling form input and displaying.
Here’s another example of creating a custom directive in Angular that’s a bit more challenging:
Example: Creating a Custom Directive for Password Strength Validation
Let’s say you want to create a custom directive that validates the strength of a password as a user types it. You should consider the password strong if it contains at least one uppercase letter, one lowercase letter, one number, and one special character.
Here are the steps to create the custom directive:
- Create a new directive using the
@Directive
decorator. The directive should use theNG_VALIDATORS
provider to register itself as a validator and should define a function calledvalidate
that performs the validation:
import { Directive } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
@Directive({
selector: '[appPasswordStrength]',
providers: [{provide: NG_VALIDATORS, useExisting: PasswordStrengthDirective, multi: true}]
})
export class PasswordStrengthDirective implements Validator {
validate(control: AbstractControl): {[key: string]: any} | null {
const value = control.value || '';
const hasUppercase = /[A-Z]/.test(value);
const hasLowercase = /[a-z]/.test(value);
const hasNumber = /\d/.test(value);
const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);
const passwordValid = hasUppercase && hasLowercase && hasNumber && hasSpecialChar;
return passwordValid ? null : { 'passwordStrength': true };
}
}
In this example, we’ve created a custom directive called PasswordStrengthDirective
. The selector
specifies the attribute that should be used to apply the directive to an input field. We’re using the NG_VALIDATORS
provider to register the directive as a validator, and defining the validate
function that performs the validation.
- Use the directive in your component’s template. You’ll also need to import the
ReactiveFormsModule
in your module to use theFormControl
class:
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { PasswordStrengthDirective } from './password-strength.directive';
@NgModule({
declarations: [
PasswordStrengthDirective
],
imports: [
ReactiveFormsModule
]
})
export class AppModule { }
<input type="password" name="password" appPasswordStrength [(ngModel)]="password">
<div *ngIf="password.invalid && (password.dirty || password.touched)">
<div *ngIf="password.errors.passwordStrength">
Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.
</div>
</div>
In this example, we’ve added the appPasswordStrength
directive to an input field that’s bound to a password
property on our component. We’ve also added some validation messages to display when the password is invalid.
Now, when the user types a password into the input field, the validate
the function is called to determine whether the password is strong enough. If the password is not strong enough, an error is added to the password
control, which is displayed to the user.
This example demonstrates how you can create a custom directive in Angular to perform validation on user input.
It’s a bit more challenging than the previous example, but it’s a great way to learn how to use directives to add custom behavior to your application.
For more details, visit the official site of Angular
Check out other topics that might interest you.
- Upload Files and Model Data with Angular and .NET Core Web API to Single Endpoint
- Remove server header from web api response
- Boosting Performance in Your .NET Core Application with Caching
- How to solve Http Error 500.19 Internal Server Error in windows server IIS for Dotnet Core application
I hope this example helps you understand how to create custom directives in Angular and how to use them in real-time scenarios. With directives, you can create powerful and reusable components that can make your Angular applications more modular and easier to maintain.