Last updated Nov 6, 2024

How to Create Custom Angular 20+ Directives: A Step-by-Step Guide

Build powerful custom directives in Angular 20+.

How to Create Custom Angular 20+ 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! 💡

What are Angular Directives? 

In Angular, directives allow us to attach custom behavior to HTML elements. There are two main types:

  1. Attribute Directives: Modify the appearance or behavior of an element.
  2. 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:

<p appHighlight="lightblue">This text is highlighted! 🎨</p>
<p appHighlight="lightgreen">And this text has a green highlight! 🌱</p>

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<any>, 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:

<div *appShowForRole="'admin'">Welcome, Admin! 👑</div>
<div *appShowForRole="'guest'">Hello, Guest! 🌟</div>

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:

  1. Keep it focused: Directives should be specific to a single task.
  2. Use inputs and outputs: Inputs let you customize behavior, and outputs let you emit events for interaction.
  3. 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! 🎉

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.