How to Create Custom Angular 18+ Directives: A Step-by-Step Guide
Creating custom directives in Angular is like adding superpowers to your HTML elements. 🦸‍♂️🦸‍♀️ With Angular directives, you can extend the power of your templates by creating reusable, custom functionality. Today, I'll walk you through the process of building your own Angular 18+ custom directives with clear examples and practical tips. Let’s dive in! 💡
Table of Contents
What are Angular Directives?
In Angular, directives allow us to attach custom behavior to HTML elements. There are two main types:
- Attribute Directives: Modify the appearance or behavior of an element.
- Structural Directives: Change the structure of the DOM (e.g., add, remove, or update elements).
Example: Think of a structural directive like *ngIf
as a “bouncer” at a club. If you meet the conditions, you’re allowed in; if not, you're kept out! 🚪👮
Why Use Custom Directives?
Sometimes, built-in directives (ngIf
, ngFor
, etc.) might not be enough for your needs. Custom directives let you:
- Reuse complex logic across your app.
- Improve code readability.
- Minimize the need for repetitive functions or classes.
Let’s get our hands dirty by creating two custom directives: a simple highlight attribute directive and a structural directive that will control element visibility based on a user role.
Setting Up Your Angular Project
First, let’s start with a new Angular 18+ project. If you don’t already have Angular CLI installed, you can install it with:
npm install -g @angular/cli
Next, create a new project:
ng new custom-directives
cd custom-directives
ng serve
You should see a basic Angular app up and running. Now, let's add some custom directives!
Step 1: Create an Attribute Directive
Our first directive will highlight text based on a custom color. This is an attribute directive because it changes an element’s appearance without altering its structure.
1.1 Generate the Directive
Run the following command to create a directive called highlight
:
ng generate directive highlight
This creates two files, highlight.directive.ts
and highlight.directive.spec.ts
, inside the src/app
directory. Let’s jump into highlight.directive.ts
.
1.2 Implement the Directive
Open the directive file and add the following code:
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
@Input() appHighlight: string = ''; // color input
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
// Apply background color
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', this.appHighlight || 'yellow');
}
}
Here, we use @Input
to accept a color, so when the directive is applied, it changes the background color to the specified value.
1.3 Use the Directive in a Component
In your app.component.html
, add the directive:
This text is highlighted! 🎨
And this text has a green highlight! 🌱
Now, when you reload the page, you’ll see each <p>
tag has a custom background color. 🎉
Step 2: Create a Structural Directive
Let’s create a structural directive that will render elements based on user roles. This will be helpful if you want to conditionally display content, like admin-only features.
2.1 Generate the Directive
Run this command to generate the new directive:
ng generate directive showForRole
2.2 Implement the Directive
In the show-for-role.directive.ts
file, add the following:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appShowForRole]'
})
export class ShowForRoleDirective {
@Input() set appShowForRole(role: string) {
if (role === 'admin') {
this.vcRef.createEmbeddedView(this.templateRef);
} else {
this.vcRef.clear();
}
}
constructor(private templateRef: TemplateRef, private vcRef: ViewContainerRef) {}
}
We use @Input
to check the provided role. If the role matches "admin", the directive displays the content. Otherwise, it hides it.
2.3 Use the Directive in a Component
In your app.component.html
, use the directive as follows:
Welcome, Admin! đź‘‘
Hello, Guest! 🌟
Only the “Welcome, Admin!” message will display if the role
condition is met.
Going Further: Reusability and Flexibility
Custom directives can be enhanced for added flexibility. For example, you could modify the appShowForRole
directive to accept an array of roles or add logic for showing/hiding elements based on multiple conditions.
Best Practices for Directives
Here are a few tips for creating effective Angular directives:
- Keep it focused: Directives should be specific to a single task.
- Use inputs and outputs: Inputs let you customize behavior, and outputs let you emit events for interaction.
- Write tests: Custom directives often handle core logic, so unit tests ensure they perform as expected.
Wrapping Up
With Angular 18+, building custom directives can improve your app’s flexibility and maintainability, while also keeping your HTML clean. Whether you need custom highlighting or user-role-based content control, directives allow you to tailor functionality to your needs.
Happy coding! 🎉