by Sai gowtham

How to create the Custom Directives in Angular

How to create the Custom Directives in Angular

In this tutorial, we are going to learn about how to create and use custom directives in angular with the help of examples.

What are Directives?

Directives are custom HTML attributes which tells 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.

Open your terminal and run the below command to generate a new directive.

ng generate directive emoji

Now, you can see two new files emoji.directive.ts,emoji.directive.spec.ts that are generated by the angular cli.

angular-directive-file

Open your emoji.directive.ts file and replace with the 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.

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

Inside the ngOnInit() lifecycle hook method we are accessing the element and adding the victory hand emoji to that element textContent.

Using custom directive

Let’s use our custom directive appEmoji 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 the appEmoji directive instead of using the same emoji, 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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course