Overview Of Directives In Angular 2 - Day Four

In Angular 1.x, we say that “Directives extend the HTML with new attributes” but now, in Angular 2, we can’t describe directives as we previously did. In Angular 2, the directives are more flexible and provide many features that we missed in Angular 1.x.


In Angular 2, components are just one type of directives. When we render any component in a template file, actually it is a instruction to Angular that at this place, we want to use “this” particular component and render the template section of this component here.


In the above image, we use “ngFor” directive which is an instruction to Angular to loop through each value of technology items and perform the below operation and/or task.

Types of Directives in Angular 2

In Angular 2, we have three types of directives.

  • Attribute Directives
  • Structural Directives
  • Component Directives

Attribute Directives

Attribute directives change the behavior and appearance of an element. Example of attribute directive is “ngClass”,”ngStyle” etc.

Example

App.component.ts

  1. import { Component,Input,Output,EventEmitter } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: '[app-root]',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8.   
  9.   
  10. export class AppComponent {  
  11.   name:String = 'This is directive example';  
  12.   
  13.   
  14.   ChangeValue(data:String){  
  15.     this.name=data;  
  16.   }  
  17.   
  18.   technology=[  
  19.   {name:"Asp.NET MVC", experience:"1 Years"},  
  20.   {name:"Android", experience:"1 Years"},  
  21.   {name:"Ionic", experience:"6 Months"},  
  22.   {name:"Angular", experience:"1 Years"},  
  23.   {name:"Node.js", experience:"6 Months"}  
  24.   ];  
  25.   
  26.   
  27. }   

App.component.html 

  1. <div [ngStyle]="{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}">  
  2. <h3 [ngStyle]="{'color':'#42f46e','font-size':'26px'}">  
  3.      {{name}}   
  4. </h3>  
  5. <h3>I am working on these technologies</h3>  
  6. <table [ngClass]="'table'">  
  7.     <tr><th>Technology</th><th>Experiences</th></tr>  
  8.     <tr *ngFor="let data of technology">  
  9.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  10.     </tr>  
  11. </table>  
  12. </div>   

App.component.css

  1. .customStyle{  
  2.     color: blue;  
  3.     font-size: 24px;  
  4.     width:300px;  
  5.     height: 30px;  
  6.     margin-top: 50px  
  7. }  
  8.   
  9. .table{  
  10.     font-size: 24px;  
  11.     font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif;  
  12.     color:white;  
  13.     margin-left: 100px  
  14.      
  15. }  
  16.   
  17. .table tr:nth-child(even) {  
  18.     background-color: #87b793;  
  19. }  
  20.   
  21. .table tr:nth-child(odd) {  
  22.     background-color: #a187b7;  
  23. }  

Output


In app.component.html page, we use “ngStyle” attribute directive to implement the inline CSS and “ngClass” attribute directive for implementing the class style for table.

Custom Attribute Directive

Now, we will create our own custom attribute directive. To create a directive, run “ng generate directive custom” command. This command creates a directive named “custom”.


When you open “custom.directive.ts” file, you will get the following code.


In the above code, “@Directive” is metadata that defines this class as directive. Now, replace the above code with this one.

  1. import { Directive,ElementRef,Renderer } from '@angular/core';  
  2.   
  3. @Directive({  
  4.   selector: '[appCustom]'  
  5. })  
  6. export class CustomDirective {  
  7.   
  8. private element:ElementRef;  
  9. private renderref_:Renderer;  
  10.   constructor(element:ElementRef,renderref_:Renderer) {  
  11.     this.element=element;  
  12.     this.renderref_=renderref_;  
  13.     //Apply Styles  
  14.   
  15.   this.renderref_.setElementStyle(this.element.nativeElement,'background-color','yellow');  
  16.   this.renderref_.setElementStyle(this.element.nativeElement,'color','blue');  
  17.   this.renderref_.setElementStyle(this.element.nativeElement,'font-size','24px');  
  18.   this.renderref_.setElementStyle(this.element.nativeElement,'margin-top','5px');  
  19.   
  20.   
  21.   
  22.    }  
  23.   
  24. }  

Let’s understand what is happening in this code. You can see that constructor of directives contains two parameters. “ElementRef” contains the reference of host element and “Renderrer” is used to render the element with styles. In the next lines, we will add the styles for “nativeElement”. Here, nativeElement denotes the element that contains this attribute.

Now, we will use this custom attribute directive in our template page.


We have added a div element and used the custom attribute directive “AppCustom” in this div element. Now, save all changes and refresh the browser.


You can see that all the styles that we implement on this custom attribute are rendered successfully.

Add Event Listener for Custom Directives

Similar to an element, we can add event listener like ‘mouseneter’, ’mouseleave’,’click’ etc. for a custom directive. Let’s add some event listeners for our custom directive. Replace the code of your “custom.directives.ts” file with the below code. 

  1. import { Directive,ElementRef,Renderer,HostListener,HostBinding } from '@angular/core';  
  2.   
  3. @Directive({  
  4.   selector: '[appCustom]'  
  5. })  
  6. export class CustomDirective {  
  7.   
  8. private element:ElementRef;  
  9. private renderref_:Renderer;  
  10. private backgroundColor="yellow";  
  11. private fontSize="24px";  
  12. @HostListener('mouseenter') mouseenter(){  
  13.    this.backgroundColor="red";  
  14.    this.fontSize="30px";  
  15.   }  
  16.   
  17.   @HostListener('mouseleave') mouseleave(){  
  18.    this.backgroundColor="yellow";  
  19.    this.fontSize="24px";  
  20.   }  
  21.   
  22.   @HostBinding('style.backgroundColor') get ColorValue(){  
  23.     return this.backgroundColor;  
  24.   }  
  25.   @HostBinding('style.fontSize') get fontValue(){  
  26.     return this.fontSize;  
  27.   }  
  28.   
  29. constructor(element:ElementRef,renderref_:Renderer) {  
  30.   
  31.     this.element=element;  
  32.     this.renderref_=renderref_;  
  33.     //Apply Styles  
  34.   
  35.   this.renderref_.setElementStyle(this.element.nativeElement,'background-color','yellow');  
  36.   this.renderref_.setElementStyle(this.element.nativeElement,'color','blue');  
  37.   this.renderref_.setElementStyle(this.element.nativeElement,'font-size','24px');  
  38.   this.renderref_.setElementStyle(this.element.nativeElement,'margin-top','5px');  
  39.    }  
  40.   
  41.   
  42.   
  43. }   

Let’s understand the above code.

In the first line, we import the “HostListener” and “HostBinding” modules in our custom directive.


After that, using “HostBinding”, we bind two attributes of an element with the property of our directives class. The @HostBinding decorator allows us to link a directive property to an element of the host component. In the below code, we bind “backgroundColor” property with “ColorValue” element and “fontSize” property with “fontValue” element.


In the above line of code, we added two eventListener for “mouseneter” and “mouseleave” event. Whenever this event occurs, the “mouseenter” and “mouseleave” functions will be called, that are attached with these events. In these functions, we are changing values of “backgroudnColor” and “fontSize” property. As we said before, these two properties are bound with two attributes of element, so the values of these attributes will change.


When the mouse comes over, the attributes backgroundColor and fontSize will be changed.


When mouse goes out of the scope of this element, it will go back to its initial state.


Structural Directives

Structural directives are used to change the structure of an element. It alters the layout of DOM by adding, replacing, or removing the element.

Example

App.component.ts 

  1. <div [ngStyle]="{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}">  
  2. <h3 [ngStyle]="{'color':'#42f46e','font-size':'26px'}">  
  3.      {{name}}   
  4. </h3>  
  5. <h3>I am working on these technologies</h3>  
  6. <table [ngClass]="'table'">  
  7.     <tr><th>Technology</th><th>Experiences</th></tr>  
  8.     <!--       ngFor Exampl        -->  
  9.     <tr *ngFor="let data of technology">  
  10.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  11.     </tr>  
  12. </table>  
  13. <input type="button" (click)="toggle()" value="Toggle Div"/>  
  14. <br/>  
  15.   
  16. <!--       ngIf Exampl        -->  
  17. <div *ngIf="show">  
  18. <div appCustom [inputbackgroundColor]="'pink'" [pankaj]="'36px'">This is a Custom Directive</div>  
  19. </div>  
  20. <br/>  
  21. <input type="text" name="data"  [(ngModel)]="count"/>  
  22. <br/>  
  23.   
  24. <!--       ngSwitch Exampl        -->  
  25. <div [ngSwitch]="count">  
  26.     <p *ngSwitchCase="10">Your Value is 10 </p>  
  27.      <p *ngSwitchCase="100">Your Value is 100 </p>  
  28.       <p *ngSwitchDefault>Your Value is Not 10 or 100 </p>  
  29. </div>  
  30. </div>   

App.component.ts 

  1. import { Component,Input,Output,EventEmitter } from '@angular/core';  
  2.   
  3.   
  4. @Component({  
  5.   selector: '[app-root]',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9.   
  10.   
  11. export class AppComponent {  
  12.   name:String = 'This is directive example';  
  13.   count:number=10;  
  14.   show:boolean=true;  
  15.    toggle(){  
  16.     this.show=!this.show;  
  17.   }  
  18.   
  19.   ChangeValue(data:String){  
  20.     this.name=data;  
  21.   }  
  22.   
  23.   technology=[  
  24.   {name:"Asp.NET MVC", experience:"1 Years"},  
  25.   {name:"Android", experience:"1 Years"},  
  26.   {name:"Ionic", experience:"6 Months"},  
  27.   {name:"Angular", experience:"1 Years"},  
  28.   {name:"Node.js", experience:"6 Months"}  
  29.   ];  
  30.   
  31.   
  32. }   

In the above code we are using “*ngFor” directive and displaying a table data. “*ngFor” directive iterates through a loop and instantiates a template each time.

“*ngIf” directive shows and hides the DOM element as per expression value passed in the directives.


In the above line of code, we are using a “*ngIf” directive and according to the value of “show” variable, it takes decision if the div will display or hide. We are calling a “toggle()” method on click of button and in this method, we are changing the value of “show” variable.


“ngSwitch” directives work as switch statement of any other languages. It takes an expression and matches this expression value for each nested element. If any nested element matches the value, then corresponding DOM element will be displayed. If any nested element doesn’t match the expression value, then the default DOM will be displayed.


In these lines of code, we created a “ngSwitch”,”*ngSwitchcase” structure hierarchy and bound the value of “count” model to “ngSwitch” directive. Now, which “p” element will display directly depends on the value of “count” and “*ngSwitchCash” that match the value of “count” model.




Create a custom structure directive

Now, let's create an “ngNif” structure directive. This structure directive opposes the “ngIf” directive. So, add a new directive named as “ngNif”.


Add the below code in your directive's file.

  1. import { Directive,TemplateRef,ViewContainerRef,Input } from '@angular/core';  
  2.   
  3. @Directive({  
  4.   selector: '[appNgNif]'  
  5. })  
  6. export class NgNifDirective {  
  7.   
  8. @Input() set appNgNif(value:boolean){  
  9.   if(!value){  
  10.     this.viewRef.createEmbeddedView(this.temRef);  
  11.   }  
  12.   else{  
  13.     this.viewRef.clear();  
  14.   }  
  15. }  
  16.   constructor(private temRef: TemplateRef<any>, private viewRef: ViewContainerRef) {  
  17.   
  18.    }  
  19.   
  20. }  

In these lines, we defined the selector name(“[appNgNif]”) for directive. The directive's selector is typically the directive's attribute name in square brackets.


A structure directive creates an embedded View and inserts that in View container, adjacent to the element. To access the embedded View, we require " TemplateRef” class and for View container, we require “ViewContainerRef” class.

A View is a fundamental building block of the application UI. It is the smallest grouping of elements created and destroyed together. ViewContainerRef class provides a container that can contain two kinds of Views - Host Views are created by instantiating a component via createComponent, and Embedded Views are created by instantiating an embedded template via createEmbeddedView.
 
Now, our custom directives need to bind true and false property to “[appNgNif]”, that means we need an “appNgNif” input property.

In these lines of code, we created “appNgNif” set property which takes value parameter of Boolean type. In this property, we added embeddedView in ViewContainerRef if value of parameter is “false”, else we need to make ViewContainerRef empty.

Now, add the below lines in html template where you want to use this structure directive. 

  1. <div [ngStyle]="{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}">  
  2. <h3 [ngStyle]="{'color':'#42f46e','font-size':'26px'}">  
  3.      {{name}}   
  4. </h3>  
  5. <h3>I am working on these technologies</h3>  
  6. <table [ngClass]="'table'">  
  7.     <tr><th>Technology</th><th>Experiences</th></tr>  
  8.     <!--       ngFor Exampl        -->  
  9.     <tr *ngFor="let data of technology">  
  10.         <th>{{data.name}}</th><th>{{data.experience}}</th>  
  11.     </tr>  
  12. </table>  
  13. <input type="button" (click)="toggle()" value="Toggle Div"/>  
  14. <br/>  
  15.   
  16. <!--       ngIf Exampl        -->  
  17. <div *ngIf="show">  
  18. <div appCustom [inputbackgroundColor]="'pink'" [pankaj]="'36px'">This is a Custom Directive</div>  
  19. </div>  
  20. <br/>  
  21.   
  22. <div *appNgNif="show">  
  23.     <h2>NgNiF Example</h2>  
  24. <div appCustom [inputbackgroundColor]="'red'" [pankaj]="'36px'">This is a ngNif Directive</div>  
  25. </div>  
  26.   
  27. <br/>  
  28. <input type="text" name="data"  [(ngModel)]="count"/>  
  29. <br/>  
  30.   
  31. <!--       ngSwitch Exampl        -->  
  32. <div [ngSwitch]="count">  
  33.     <p *ngSwitchCase="10">Your Value is 10 </p>  
  34.      <p *ngSwitchCase="100">Your Value is 100 </p>  
  35.       <p *ngSwitchDefault>Your Value is Not 10 or 100 </p>  
  36. </div>  
  37. </div>  

When the value of “show” property becomes true, the “*ngIf” will show the div and “*appNgNif” will hide the div.


When “show” becomes false, the “*ngIf” will hide the div and “*appNgNif” will show the div.

Conclusion

Today, we learned about different types of directives and also created custom attributes and structure directives. I hope you liked this article. In the next article, we will cover some other concepts of Angular 2.


Similar Articles