Angular / Angular Directives and Pipes

Creating and Using Custom Directives

This tutorial will guide you through creating your own custom directives in Angular. We'll show how these custom directives can encapsulate and reuse code, making your application…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the use of built-in and custom directives and pipes for enhancing templates.

Creating and Using Custom Directives in Angular

1. Introduction

Goal

This tutorial aims to guide you on how to create and use custom directives in Angular.

Learning Outcomes

By the end of this tutorial, you should be able to:
- Understand what custom directives are
- Create your own custom directives
- Use your custom directives in your applications

Prerequisites

To follow this tutorial, you should have a basic understanding of Angular and TypeScript. Familiarity with Angular's built-in directives is an advantage but not necessary.

2. Step-by-Step Guide

What are Custom Directives?

Custom directives are user-defined directives that allow you to manipulate the DOM (Document Object Model). They allow you to encapsulate and reuse code in your application, making it easier to maintain and scale.

Creating a Custom Directive

Here's a basic example of creating a custom directive:

  1. First, generate a directive using Angular CLI with the command ng g directive myCustomDirective. This will create a myCustomDirective.directive.ts file.
  2. Open the myCustomDirective.directive.ts file and you'll see something like this:
import { Directive } from '@angular/core';

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirectiveDirective {

  constructor() { }

}

The @Directive decorator tells Angular that this class is a directive. The selector 'appMyCustomDirective' is used to apply the directive to an element in the template.

3. Code Examples

Example 1: Simple Custom Directive

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirectiveDirective {

  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }

}

In the above code, ElementRef is a service that grants direct access to the host DOM element through its nativeElement property. The directive sets the background color of the host element to yellow.

To use this directive, simply add it to an element in your template:

<div appMyCustomDirective>
  This div's background color is yellow.
</div>

Example 2: Custom Directive with Input

Directives can also have inputs that allow data to flow from the binding expression into the directive. Here's an example:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirectiveDirective {

  @Input('appMyCustomDirective') backgroundColor: string;

  constructor(private el: ElementRef) { }

  ngOnInit() {
    this.el.nativeElement.style.backgroundColor = this.backgroundColor;
  }

}

In this example, the directive takes an input backgroundColor and applies it as the background color of the host element. Usage:

<div [appMyCustomDirective]="'red'">
  This div's background color is red.
</div>

4. Summary

In this tutorial, you learned about custom directives, how to create them, and how to use them in your Angular applications. Directives provide a way to manipulate the DOM and encapsulate and reuse code, making your applications easier to maintain and scale.

5. Practice Exercises

Exercise 1: Create a custom directive that changes the text color of the host element.

Solution:

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirectiveDirective {

  constructor(private el: ElementRef) {
    el.nativeElement.style.color = 'blue';
  }

}

Usage:

<p appMyCustomDirective>
  This paragraph's text color is blue.
</p>

Exercise 2: Create a custom directive that takes an input and applies it as the font size of the host element.

Solution:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appMyCustomDirective]'
})
export class MyCustomDirectiveDirective {

  @Input('appMyCustomDirective') fontSize: string;

  constructor(private el: ElementRef) { }

  ngOnInit() {
    this.el.nativeElement.style.fontSize = this.fontSize;
  }

}

Usage:

<p [appMyCustomDirective]="'20px'">
  The font size of this paragraph is 20px.
</p>

I'd recommend that you practice creating more custom directives for various use cases to fully understand the concept. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Age Calculator

Calculate age from date of birth.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help