Creating custom directives in angular 8

Creating custom directives in angular 8

In this tutorial, we will learn about how to create a custom directive in angular with the help of examples.

What is a Directive?

Directives are custom HTML attributes which tell angular to change the style or behavior of the dom elements.

Creating custom directive

We are creating a custom directive called emoji which helps us to add emojis to our HTML elements.

Now open your terminal and run below command to generate a new directive.

ng generate directive emoji

Now you can see two new files are generated by the angular cli.

angular-directive-file

Open your emoji.directive.ts file and replace with below code.

emoji.directive.ts
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
  selector: '[appEmoji]'})
export class EmojiDirective implements OnInit {

  constructor(private el: ElementRef) {}

   ngOnInit() {
    this.el.nativeElement.textContent +='✌️';  }
}

In the above code, first we imported Directive decorator and ElementRef type from the @angular/core package.

@Directive method accepts objects as its first argument where we need to define the name of our directive selector: '[appEmoji]'

Inside the ngOnInit lifecycle hook method we are accessing the element where we use our directive and adding the waving hand emoji to that element textContent.

Using our custom appEmoji directive

Let’s use our custom directive inside the app component.

app.component.html
<div style="text-align:center">
  <h1 appEmoji>Welcome to Angular</h1></div>

output

angular-emoji-directive-usage

Passing values to a custom directive

We can also pass our own emojis to our appEmoji directive instead of using the same emoji always for that we need to import the @Input decorator.

emoji.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
  selector: '[appEmoji]'})
export class EmojiDirective implements OnInit {

  @Input('appEmoji') emoji: string;
  constructor(private el: ElementRef) { }

  ngOnInit() {
    this.el.nativeElement.textContent += this.emoji;  }
}

Usage

app.component.html
<div style="text-align:center">
  <h1 appEmoji="👌">Welcome to Angular</h1></div>

passing-values-emoji-directive