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.
Open your emoji.directive.ts
file and replace with the below code.
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.
<div style="text-align:center">
<h1 appEmoji>Welcome to Angular</h1></div>
Output
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.
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
<div style="text-align:center">
<h1 appEmoji="👌">Welcome to Angular</h1></div>