Custom Directives in Angular 7

alert and animations in angular js , 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.

<figure class="wp-block-table is-style-regular"><table><tbody><tr><td>1</td><td>constructor(el: ElementRef)</td></tr></tbody></table></figure>

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.

123
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.

1

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

app.component.html

12345678<!–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

<figure class="wp-block-table is-style-regular">import { Directive, ElementRef, Input, OnInit } from '@angular/core';&nbsp;@Directive({&nbsp;&nbsp;selector: '[appColor]'})export class ColorDirective implements OnInit {&nbsp;&nbsp;@Input() appColor: string;&nbsp;&nbsp;&nbsp;constructor(private el: ElementRef) { }&nbsp;&nbsp;&nbsp;ngOnInit(){&nbsp;&nbsp;&nbsp;&nbsp;this.el.nativeElement.style.backgroundColor = this.appColor;&nbsp;&nbsp; }}<table class=""><tbody></tbody></table></figure>

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

1import { 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.

1export class ColorDirective implements OnInit

Let’s create an input property in our directive named same as our directive name.

1@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.

123ngOnInit(){    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

123456789<!–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.

12<p [appColor]= “‘green'”>Show me Green Color</p><p [appColor]= “‘red'”>Show me Red Color</p>

Note: String values must be passed with single quotes (‘) with double quotes (“).

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

123456789101112import { 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

123456789<!–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.

Tags: website development company in delhi|| website designing company in delhi || Website Developer in Delhi || magento development company in delhi ||  web developer in delhi

About Post Author