Custom Directives in Angular 7

Custom Directives in Angular 7

Loading

Getting started with Angular 7 Directives

Custom Directives in Angular 7 are the most powerful feature of any Angular 7 applications. In fact, the most commonly used feature, which is composed, is itself a Custom directive. There are basically three types of directives:

  • Component directive โ€“ a directive with templates.
  • Attributeย directive โ€“ ย a directive that manipulates DOM by changing behavior and
  • Appearance directive โ€“ a directive that creates and destroys the DOM element

Component directive is what we are using it in our day to day programming since Angular 2. So, I am going to skip discussing about Component the directive. In this post, we will briefly discuss the rest of the two directives: Attribute and Structural directives.

Structural Angular Directives

Structural directives are used to add, remove or manipulate the elements from the DOM. It is easy to identify structural directives. Structural directives are prefixed by an asterisk (*) with the directive name. Example of structural directives are : NgIfNgSwitch & NgFor. These are inbuilt structural directives.

Attribute Angular Directives

Attribute directives are used to change the behavior and appearance of an DOM element. As the name suggests, they are applied as an attribute on the DOM element.

<p [style.color]=โ€โ€˜red'โ€>attribute directive</p><p [hidden]=โ€shouldHideโ€>attribute directive</p>

Custom Angular Directive

Letโ€™s create our first custom directive. To generate the directive, run this command in the command terminal.

ng generate directive color

This command will generate a color.directive.ts file in the app folder.

color.directive.ts

import { Directive } from โ€˜@angular/coreโ€™; @Directive({  selector: โ€˜[appColor]โ€™})export class ColorDirective {   constructor() { } }

In the first line, Angular CLI imported Directive from @angular/core package. This will provide the @Directive decorator.

The name of our directive is appColor in the [] selector. Angular will look for this attribute on the HTML element and applies the directive logic to that element. This directive has a class name ColorDirective.

This command will also add an entry in our app.module.ts file as well. See the line 7 and 13 in app.module.ts file.

app.module.ts

Letโ€™s put some code logic in our appColor directive. We are going to make the background color of an element Red. So, our directive code looks like this:

color.directive.ts

import { Directive, ElementRef } from โ€˜@angular/coreโ€™; @Directive({  selector: โ€˜[appColor]โ€™})export class ColorDirective {   constructor(el: ElementRef) {     el.nativeElement.style.backgroundColor = โ€˜redโ€™;  }}

If you notice in line first, we also imported ElementRef

import { Directive, ElementRef } from โ€˜@angular/coreโ€™;

and injected this in our directive class constructor in order to access the element, on which this directive is applied.

constructor(el: ElementRef)

After injecting ElementRef in our class constructor, we can now access the element here. So, letโ€™s access the element and set its background color to Red.

constructor(el: ElementRef) {     el.nativeElement.style.backgroundColor = โ€˜redโ€™;  }

This is how, we can create our basic directive. But how can we use it on any element? To apply this directive, we have added appColor to <p></p> element.

<p appColor>Show me my color</p>

See the complete code of app.component.html file.

app.component.html

<!โ€“The content below is only a placeholder and can be replaced.โ€“>
  <div style=โ€text-align:centerโ€>  <h1>    Welcome to {{ title }}!  </h1> <p appColor>Show me my color</p><router-outlet></router-outlet></div>

Open the browse and see the page.

Here, we can see, our directive changed the red background colour of the text.

So, in this way, we have modified the DOM through our custom directive. We have changed the colour of the p element through angular attribute directive.

Passing value to Custom Directive

In the above directive, we have hardcoded the color code Red. It would be great, if we can make it dynamic, i.e, our directive can accept any color name from the element and render the background in the same color. In order to make our custom directive dynamic, letโ€™s tweak our code again.

Custom Directives in Angular 7

color.directive.ts

import { Directive, ElementRef, Input, OnInit } from โ€˜@angular/coreโ€™;ย @Directive({ย ย selector: โ€˜[appColor]โ€™})export class ColorDirective implements OnInit {ย ย @Input() appColor: string;ย ย ย constructor(private el: ElementRef) { }ย ย ย ngOnInit(){ย ย ย ย this.el.nativeElement.style.backgroundColor = this.appColor;ย ย  }}

In the line first, we have further imported OnInit from @angular/core

import { Directive, ElementRef, Input, OnInit } from โ€˜@angular/coreโ€™;

OnInit

A lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. Define an ngOnInit() method to handle any additional initialization tasks.

After importing OnInit, we implemented this directive in our class in line 6.

export class ColorDirective implements OnInit

Letโ€™s create an input property in our directive named same as our directive name.

@Input() appColor: string;

Then implements the ngOnInit() method. In this method, we wrote the code of setting the background color of an element to the color, passed through element to our directive.

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

Now, letโ€™s see the code in our html template file, how to use this directive now.

app.component.html

<!โ€“The content below is only a placeholder and can be replaced.โ€“><div style=โ€text-align:centerโ€>  <h1>    Welcome to {{ title }}!  </h1> <p [appColor]= โ€œโ€˜green'โ€>Show me Green Color</p> <p [appColor]= โ€œโ€˜red'โ€>Show me Red Color</p><router-outlet></router-outlet></div>

See these two lines in our template file. We have passed green & red color to <p></p> elements.

<p [appColor]= โ€œโ€˜green'โ€>Show me Green Color</p><p [appColor]= โ€œโ€˜red'โ€>Show me Red Color</p>

Now, open the browser and see the page.

Passing value to Custom Directive by Component Class

To make our above code more simpler, we can declare two model property in our component class app.component.ts file.

app.component.ts

import { Component } from โ€˜@angular/coreโ€™; @Component({  selector: โ€˜app-rootโ€™,  templateUrl: โ€˜./app.component.htmlโ€™,  styleUrls: [โ€˜./app.component.cssโ€™]})export class AppComponent {  title = โ€˜zeptoappโ€™;  greenColor = โ€˜greenโ€™;  redColor = โ€˜redโ€™;}

Now, you can see in line 10 & 11, we have created two model properties: greenColor & redColor. Then, we passed it to our custom directive through html template file.

app.component.html

<!โ€“The content below is only a placeholder and can be replaced.โ€“><div style=โ€text-align:centerโ€>  <h1>    Welcome to {{ title }}!  </h1> <p [appColor]= โ€œgreenColorโ€>Show me Green Color</p> <p [appColor]= โ€œredColorโ€>Show me Red Color</p><router-outlet></router-outlet></div>

In this way, we can pass custom directive values from the component class as well.

Summary

In this blog, we looked into different kinds of Custom Directives in Angular 7. And then we have created our custom directive. We also learned about how to pass value from HTML template file, and then from component class as well.

About Post Author