Exploring AngularJS Directives in Detail

Introduction 

 
Gone are the days when people used to write every piece of code manually to apply any particular feature or functionality in the application. Now, programming languages have become efficient as the requirements of effectively writing code is increasing. To apply a particular effect in your program, you don't have to write a particular code snippet recursively. Now, you can dynamically manipulate programming language to apply effects automatically without writing the same code all the time. When it comes to AngularJS programming language, it has directives that can dynamically improve your programming experience by making it more productive and effective at the same time. Being one of the most consistent AngularJS development agencies in the market, we are going to share important things about AngularJS directives that you can use and improve your AngularJS programming skills. So without further ado, let's explore AngularJS directives in detail.
 
First, we will start with an overview of AngularJS directives.
 

What are AngularJS Directives?

 
AngularJS directive can be extremely helpful and powerful components of Angular JS programming language. AngularJS directives make DOM elements editable. You can manipulate DOM elements by attaching a particular behavior through AngularJS directives. These Angular JS directives are used to convert DOM elements for particular tasks. Any company will give preference to the learning of this subject. Whenever you want to make your HTML elements reusable, AngularJS directives can help you do that. You can also make your code testable through AngularJS directives.
 

How to Use AngularJS Directive?

 
Every AngularJS directive has a predefined name like ng-repeat. You can also apply a custom name to your AngularJS directive and call it anything you like. These Angular JS directives are used in one of the elements and attributes, comments or classes of your AngularJS programming language. They have also got several types, let’s look at them below.
 

Types of AngularJS Directives

 
There are basically three different types of AngularJS directives.
 
Components
 
Components are made from templates. At the core, components used the same directive API and provide a straightforward approach to users to define them.
 
Attribute Directives
 
This AngularJS directive type does not have any templates and it is specifically working around manipulating the DOM.
 
Attribute directives usually change the behavior and look-and-feel of the DOM.
 
This is one of the most important directives that can help us implement conditional styles to elements to dynamically improvise their behavior according to our needs.
 
Structural Directives
 
These directives are critically designed to make or delete DOM elements as required. In fact, directives are one of the reasons why AngularJS for Enterprise App is a perfect combo. Unlike attribute directives briefed above, structural directive takes a different approach and work directly on the DOM. Instead of changing the behavior of the element of the DOM, structural directives straightaway add or destroy the elements. Thus, while implementing structural directives, developers have to be very mindful. Now, let’s explore how can we develop attribute and structure directives.
 
Let's create an attribute directive first.
 

How to Build Attribute Directive?

 
When you create the AngularJS directive, you follow almost the same process as creating a component. A developer can forget the process and focus on end-result. But, in the case of directives, you should not forget the process. Right now, we will create a directive called my-programming which will highlight the red background of an element to show the error in the code.
 
I hope you have already installed AngularJS and other repositories required for the tasks.
 
Now let's create a file named app.myerrordirective.ts on the folder src/app. Then you can add below code snippet inside it.
  1. import {Directive, ElementRef} from '@angular/core';  
  2.    @Directive({  
  3.    selector:'[my-error]'  
  4.    })  
  5.    export class MyErrorDirective{  
  6.       constructor(elr:ElementRef){  
  7.       elr.nativeElement.style.background='red';  
  8.    }  
  9. }  
Now, we will require a selector that will give a name to our directive. We will call it my-error. Then, we will create a class named MyErrorDirective to acquire access to the DOM. We will also use ElementRef to do the task effectively. Now, we will add the code for highlighting the constructor of the class.
 
We will go to the declaration in the app.module.ts file to use this directive:
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { MyErrorDirective } from './app.myerrordirective';  
  4. import { AppComponent } from './app.component';  
  5. @NgModule({  
  6.    imports: [ BrowserModule ],  
  7.    declarations: [ AppComponent, MyErrorDirective ],  
  8.    bootstrap: [ AppComponent ]  
  9.    })  
  10. export class AppModule { }  
 Now, go to the app.component.ts file and add the below code snippet inside it.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'my-app',  
  5.   template: `<h1 my-error>Hello {{name}}</h1>`,  
  6. })  
  7. export class AppComponent  { name = 'Angular'; }   
Save the file, go to the Google Chrome browser and type the URL to get Hello Angular written in the red background.
 
Now, let’s create a structural directive.
 

How to Create a Structural Directive?

 
Just like we created an attribute directive in the above section, we will use the same approach for creating a structural directive. In order to get a structural directive, we would add a copy of the ngIf directive. Now, let's begin the process by going to the app.mycustomifdirective.ts file.
  1. import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';   
  2.    @Directive({  
  3.    selector: '[myCustomIf]'  
  4. })  
  5. export class MyCustomIfDirective {  
  6.    constructor(  
  7.       private templateRef: TemplateRef<any>,  
  8.       private viewContainer: ViewContainerRef) { }  
  9.       @Input() set myCustomIf(condition: boolean) {  
  10.       if (condition) {  
  11.          this.viewContainer.createEmbeddedView(this.templateRef);  
  12.       } else {  
  13.    this.viewContainer.clear();  
  14.    }  
  15.  }  
We have used several imports for this particular example ViewContainerRef, TemplateRef, and Input.
 
ViewContainerRef is the container to attach multiple views. The TemplateRef is used to initiate embedded views to represent a particular area of the user interface to be rendered which is linked to a template. Finally, the Input import is used to pass the data to the component.
 
Now, it is time to add it to the decorators.
  1. import { NgModule }      from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { MyErrorDirective } from './app.myerrordirective';  
  4. import { MyCustomIfDirective } from './app.mycustomifdirective';  
  5.   
  6. import { AppComponent }  from './app.component';  
  7.   
  8. @NgModule({  
  9.   imports:      [ BrowserModule ],  
  10.   declarations: [ AppComponent, MyErrorDirective, MyCustomIfDirective ],  
  11.   bootstrap:    [ AppComponent ]  
  12. })  
  13. export class AppModule { }  
Then, write the below code to use it in the component.
  1. import { Component } from '@angular/core';  
  2. @Component({  
  3. selector: 'my-app',  
  4. template: `<h1 my-error>Hello {{name}}</h1>  
  5. <h2 *myCustomIf="condition">Hello {{name}}</h2>  
  6. <button (click)="condition = !condition">Click</button>`,  
  7. })  
  8.   
  9. export class AppComponent {  
  10. name = 'Angular';  
  11. condition = false;  
  12. }  
Structural directives provide the most helpful and useful approach to have dynamic programming experience. It allows us to let us know when we have to showcase unique data to different end-users into the DOM based on the type of permissions they have given. For example, a website editor will have different permissions compared to the owner of the website. The developer of the website would have different access to the website compared to the person who is the author of an article on the website. So, if we have uploaded confidential information into the DOM using attribute directives, all the types of users would access all the information. In order to avoid such a hazardous user experience, you can leverage attribute directives accordingly. Now, you might wonder about the core differences between structural and attribute directives, and you might be thinking where and when should I use each of them.
 
Most of our programming objectives AngularJS can be achieved through any of the directives, but that doesn't mean that you go with either of them without brainstorming. With the introduction of Angular8, directives will have a special place in AngularJS. If you use either one of them, you will have problems in the future and have to adjust by the limitation and complexity provided by respective directives. Therefore, let's understand how these directives a different and when to use them.
 
If an AngularJS element that has the directive and will still be required in the DOM, then we must keep it. So, in this particular scenario, we have to go with the attribute directive. In another scenario, if the element doesn’t have used, then we have to remove it through a structural directive. Sometimes the developer goes over-the-board and hides directives just to make the DOM look clear and comprehensible. This is the biggest mistake that they do and end up creating complexities in their AngularJS source code. You don't need to hide all the elements just to make the overall appearance minimalist and clean. If you hide most of the DOM elements, it would make your code complex and even impact on the performance of your AngularJS application. So, you have to determine which particular directive has the least impact, and then apply. Professional assistance can be helpful to carefully brainstorm, analyze and determine the performance of your application and choose which directive to go with.
 

Conclusion

 
So far, we have discussed what are AngularJS directives, their types, and when you use them. We also created two directives.
 
I hope you found this article helpful and would love to know your feedback about this blog post. So, feel free to discuss and share your thoughts in the comments below.