Custom Angular Directives

Subscribe to my newsletter and never miss my upcoming articles

Angular allows the user to create custom Directives, Directives are the ability, that Angular give us as way to attach custom behavior to DOM elements. You will normally see this in the HTML document attached as decorators.

example:

<li appDeleteFromDom >Item line 1</li>

in the above example we have appDeletFromDom as decorator, this decorator will be activated when the user clicks on that specific li element

In this article, I will create a simple Directive whose only function will be to delete a clicked li from the DOM. It will animate the clicked li and after half a second it will remove it from the DOM.

This Directive is dynamic, as it will respond to the user, via listening mouse events, and responding by setting or removing the desired attribute behavior for that specific DOM element.

The dynamic part of this directive is accomplished by adding HostListener to the list of imports.

Let us get our hands dirty with the code. As usual the very first thing we should do is define the HTML template. See code below.

app.component.html

<h1>ANGULAR DIRECTIVES EXAMPLE </h1>
<h4>Angular version: <strong>{{ name | uppercase}}</strong></h4>
<p>Deleting DOM elements, using directives<p>
        <p>Click to delete</p>

        <ul class="lista">
            <li appDeleteFromDom>Item line 1</li>
            <li appDeleteFromDom>Item line 2</li>
            <li appDeleteFromDom>Item line 3 </li>
            <li appDeleteFromDom>Item line 4 </li>
            <li appDeleteFromDom>Item line 5 </li>
            <li appDeleteFromDom>Item line 6 </li>
            <li appDeleteFromDom>Item line 7 </li>
            <li appDeleteFromDom>Item line 8 </li>
            <li appDeleteFromDom>Item line 9 </li>
            <li appDeleteFromDom>Item line 10 </li>
        </ul>

In the above code, we only create a page with an unordered list with 10 li's. Notice that each li is decorated with appDeleteFromDom, that means that whenever the user clicks on that specific li, some kind of custom behavior will be applied to it. in our case the li will be deleted after some fanfare.

The appDeleteFromDom is nothing else but the selector from our custom directive. see code excerpt.

@Directive({
  selector: "[appDeleteFromDom]"
})

app.component.ts

Now Let us work on the app.component.ts from project. This file is the default file created when we generated the project. So it will not change from its default.

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
}

app.module.ts

Then we have app.module.ts, this file is were we are telling angular that we will be using a custom directive.

We will add the following line:

import { DeleteFromDomDirective } from "./delete-from-dom.directive";

We will add DeleteFromDomDirective to the following line. (added at end of line)

declarations: [AppComponent, HelloComponent, DeleteFromDomDirective],

finally just before we talk about our custom Directive, I will show you the CSS definitions. (basic formating to the DOM elements)

* {
  font-family: Lato;
  list-style-type: none;
}

html {
  font-size: 62.5%;
  scroll-behavior: smooth;
}

li {
  padding: 7px 0 7px 20px;
}

li:hover {
  color: deeppink;
  font-size: 1.5rem;
}

li:nth-child(even) {
  background-color: cornsilk;
}

li:nth-child(odd) {
  background-color: rgb(216, 216, 215);
}

Now Let's focus on the main objective of this article. The custom Directive. to create the directive I used the following command:

ng generate directive delete-from-dom

Notice I did not use directive word in the name. It will be added by angular. So the full name will be delete-from-dom.directive.ts

The directive code, will be using the following: Directive: angular interface to make this class a directive by using the @Directive decorator.

ElementRef: This point to the just clicked element

HostListener: This is just listening and detecting user/mouse events

Renderer2: This takes care of repainting the screen after a DOM element changes its behavior, added or removed

We will be listening for a mouse click. As soon as we detect a click on any given li we go ahead an execute deleteLi method.

import { Directive, ElementRef, HostListener, Renderer2 } from "@angular/core";

@Directive({
  selector: "[appDeleteFromDom]"
})
export class DeleteFromDomDirective {
  constructor(private elmenetRef: ElementRef, private renderer: Renderer2) {}

  @HostListener("click", ["$event"])
  deleteLi(): void {
    this.renderer.setStyle(
      this.elmenetRef.nativeElement,
      "background",
      "orange"
    );
    this.renderer.setStyle(
      this.elmenetRef.nativeElement,
      "transition",
      "1s linear all"
    );
    this.renderer.setStyle(
      this.elmenetRef.nativeElement,
      "transform",
      "scale(1.7)"
    );

    setTimeout(() => {
      this.elmenetRef.nativeElement.remove();
    }, 500);
  }
}

Please see live code here

Thanks for reading this article.

Let's Connect

Twiter

Rueda Tech

Next Article: Undecided

No Comments Yet