Brief Introduction To Directives In Angular Framework

Posted By : Mahima Gautam | 11-Feb-2020

 angular

In the angular application, the directives are considered to be quite important and as we think on it the most used angular unit, the component in the angular is a directive. The angular component is nothing more than a directive with the template. Directives are considered to be the building blocks in the angular environment. The directive is considered to be the function that gets compiled whenever the angular environment finds it in the DOM. It helps to extend the power of HTML just by giving the new syntax to it. Every directive has a name, that name can be from angular predefined like ng-repeat, or we can have a customized one. Each directive sees where they can be used will it be in the element, attribute, class or comment. From angular 2 above version, the directives are separated into three types.

 

Components

As we have seen, components are nothing but directives with templates. They just use directive API and gives a cleaner way of defining them. 

 

The other two types of directives are made for DOM manipulation. They do not have templates.

 

Attribute Directive

These directives are used for manipulation of the DOM by changing its behavior and appearance. We generally use this directive for applying a conditional style to elements, show or hide elements or dynamically changing the behavior of the component according to a changing property.

 

Structural Directive

These directives are made for creating and destroying the DOM elements. These directives are not so friendly, as they just add or remove the elements from the DOM. So while using them, we need to be careful because we change the HTML structure.

 

Using Existing Angular Directive

To use these existing directives is very easy. The ngClass directive of angular is a good example of the existing directive. 

<p [ngClass]="{'red'=true, 'green'=false}">
    Angular Directives Are Cool!
</p>

<style>
    .red{color: red}
    .green{color: green}
</style>

 

So in the above code, the ngClass directive is adding red color to the paragraph and not adding yellow color explicitly. So it is an example of an attribute directive because we are changing the appearance of class and not the HTML structure.

 

How To Create An Attribute Directive

The way we create a component similarly the directive is created. The only difference is we use a @Directive decorator. For example, we' ll create a directive with the name "error-directive" that will highlight red in the background of an element to indicate the error. Now will create a file with name "app.errordirective.ts" in the src/app folder and will add the following code.

 

 

import {Directive, ElementRef} from '@angular/core';

@Directive({
    selector:'[error]'
})

export class ErrorDirective{
    constructor(elr:ElementRef){
        elr.nativeElement.style.background='red';
    }
}

 

To use directive import DIRECTIVE from @angular/core. We want selector, that gives a name to the selector in our example we have given name error. After that will create a class ErrorDirective. For accessing an element of our DOM, we use ElementRef. To use the above-created directive, we have to add it to the declarations on app.module.ts file: 

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ErrorDirective } from './app.errordirective';

import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, ErrorDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

 

Now to use that directive in the app.component.ts file add the following code. 

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1 error>Hello {{name}}</h1>`,
})
export class AppComponent  { name = 'First directive'; }

 

Creating Structural Directive


For creating structural directive we' ll make a copy of ngIf directive. In this way we' ll see the implementation of the directive, will also see that how angular directive handle the things from behind.

First will make app.customifdirective.ts file.

 



@Directive({
    selector: '[CustomIf]'
})

export class MyCustomIfDirective {

    constructor() { }

    @Input() set CustomIf(condition: boolean) {
        if (condition) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }
}

 


In the above example, we can see that we have used many important for this one, like Input. This input decorator has the purpose of passing the data from one component to another. TemplateRef is used for instantiating embedded views and ViewContainerRef is the container in which we can attach one or more views.


Now add the directives in the declarators.

 

import { ErrorDirective } from './app.myerrordirective';
import { CustomIfDirective } from './app.mycustomifdirective';

import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, ErrorDirective, CustomIfDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

 

 Now we can use them in our components.

 

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1 my-error>Hello {{directive}}</h1>
         <h2 *CustomIf="condition">Hello {{directive}}</h2>
             <button (click)="condition = !condition">Click</button>`,
})

export class AppComponent  {
    directive = 'Angular';
    condition = false;    
}

 

This approach of structural directives can be proved very useful when we need to show different information to different users based on permissions.


In the end there should be a question which directive should be used, Simple rule to choose between the two is what requirement you have, use directive accordingly, like if you have element that has a directive that will be used in DOM when DOM will not be visible in this case we can use attribute directive like hidden. But if the element we are using has no use, then we should remove it from the code.

About Author

Author Image
Mahima Gautam

Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.

Request for Proposal

Name is required

Comment is required

Sending message..