Directives in Angular how to create angular directives ,types of directives

 Directives in Angular how to create angular directives ,types of directives.



Hello dear visitor and learner in this article iwwill cover types of directives and how to use them and also how to create a custom directive.

Introduction to angular

Angular is a javaScript framework introduced by google .Actually this is open source full stack web application framework special developed for SPA(single page application).Angular provides many features and with the help of the this framework we can create not only web applications but also hybrid and native applications with the help of some other frameworks like IONIC ok let's move forward to the main topic i wil provide another article for ionic how we can use it to create hybrid and native applications.

types of directives in angular


What is directive ?

basically whenever we try to add some dynamic functionality in our web application we will always prefer to use jQuery or JavaScript am i right? But if we are using angular as a framework there should be some feature to handle all the dynamic feature.

   For example if we want to add a feature in our web application like  on button click show me different types colors on every different click i want see different color . For this we have to use JavaScript or jQuery as we know jQuery is the best selection for all this type of functionalities but angular also provides us to handle all this without help of angular or any other third party plugins .

  Yes , to add such kind of functionalities in our application we have to use directives .Directives are basically used modify the DOM elements and show hide feature according to the requirement and we can also change the view of the pages dynamically.

Types of Angular directives

there are three types of directives in angular 

1. Component Directives 
2. Structural Directives
3. Attribute Directives





Let's have look on each directive

1.Component Directive:-


We can simply call this directive as a component directive or directive with a template this directive helps to add a dynamic and custom template to the pages 


Syntax to create a component directive in angular 

Let's create one directive named changetext the main goal of this attribute is to change the color of the text dynamically 


Your-derctive.ts

import { Directive, ElementRef} from '@angular/core';
@Directive({
   selector: '[changeText]'
})

export class ChangeText {
   constructor(Element: ElementRef) {
      console.log(Element);
      Element.nativeElement.innerText="Your text here ";
   }
}



Here we have simply created one directive with @Directive decorator to add meta data to this ChangeTest class so the class can understand which type of class i am .And then after that we have added a ElementRef element reference this is mandatory here and then after using this element instance we can add random text as you can see above we have added a element reference just pass any text you want to this . 

app.component.html


<div style="text-align:center">
   <span changeText >Welcome to {{title}}.</span>
</div>

And inside the html page of you component just use the directive like this that's it .

Let's move forward to the 2nd directive which is 

2.Structural Directive 

This one another best directive of angular using which we can easily iterate and show huge amount of array of JSON data in the view or template. every structural directive starts with (*) symbol .

Some structural directive are 

*ngIf
*ngFor
*ngSwitch


These are mostly used directive in any size of web application.we can easily use this directive whenever we want to work with huge amount of iterable data.

Example:

*ngIf


If we want to show some element in the DOM as per the requirement so we just need to create a variable and need to set the value for that variable and that variable should be of boolean type because *ngIf only understands boolean values.

Let's assume this my component 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

showelement :boolean=true;
}

we have added a variable of boolean type which we can you later for *ngIf directive to show or hide a element.


app.component.html

<div *ngIf="showelement">show the text according to the value of the variable<div>


inside the app component we have added a div with some text and that value can only be visible when the value of that variable will true 

*ngFor

this is another nice directive in the angular structural directive specially used to show array of JSON data in the view.This directive basically iterate the bunch of data and show them in the elements .

For example if i have a array of JSON object and want to show the object key values in the table dynamically.

JSONobject= {
"name":"John",
"age":30,
"car":null
}

So first of all we have to store this json object inside a any type of array like this .

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
Dataarray :any=[];

JSONobject= {
"name":"John",
"age":30,
"car":null
}

this.Dataarray =  jsonobject;

}

now our Object is ready to iterate with the help of *ngFor

<table>
<th>.....
<tr *ngFor="let item of Dataarray">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
.....
</tr>
</table>

Here we have done iteration of the array with help of the *ngFor 

taken a variable let item which will get each key value from the array and we can show them using string interpolation {{item.name}}......


3.Attribute Directive


Attribute directives are basically used to change the look and behavior of the view elements.

Some examples are 

ngStyle
ngClass

These attributes are used to dynamically add behavior to the view like if we want to add some specific style and design on particular condition then we can use these directive to achieve that.

Example of Custom attribute directive:-


Lets assume we have generated a directive like this 

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

@Directive({
  selector: '[colorhighlight]'
})
export class ColorHighLight {
    constructor(private el: ElementRef) {
       this.el.nativeElement.style.backgroundColor = 'red';
    }
} 



this the process we have implemented above for component directive and now we can use this as attribute like we use the attribute inside elements like disable ,style,text,value all this things .


<p colorhighlight>invalid attempt....!</p>

for more details please add comment below or contact us ,,,,,,











Post a Comment

Previous Post Next Post