Explore Directives In Angular2

Directives are just an instruction to the compiler (like components ,selectors of html tags) which tell Angular 2 what to do at certain places in your code. Directives are key parts which not only allow us to render views with the help of components but also allow us to change the general appearance and also the structure of the DOM.

So in this blog post, we will learn how to use Directives in Angular 2.

Directives

Essentially, there are three types of directives in Angular 2 as shown in the  figure below.

Directives

Attribute Directives

They interact with the element to which they are applied.(e.g. change the style). They are named attribute directives because they are applied like a HTML element attribute. For Example ( ).

Note

Directives don't have Property or Event Bindings.

Example of Attribute Directives are as follows:

  • ngClass

First create one component using angular-cli. which will create boiler plate for us; for example, if we are creating a component with the help of the following command

cmd > ng g c directives

It will create directives.component.html,directives.component.css,

directives.component.ts,directives.component.spec.ts

Now change .css file and write the following code.

  1. .border {  
  2.     border: 3 px solid blue;  
  3. }.background {  
  4.     background - color: green;  
  5. }  
  6. div {  
  7.     width: 100 px;  
  8.     height: 100 px;  
  9. }  
Then in .html file write these.
  1. <h1>Attribute Directives</h1>  
  2. <h2>ngClass/ngStyle</h2>  
  3. <div [ngClass]=”{border: false, background: true}”></div>  
And Output will be

Directives

 

  • ngStyle
    1. <h1>Attribute Directives</h1>  
    2. <h2>ngClass/ngStyle</h2>  
    3. <div [ngStyle]=”{‘background-color’: ‘red‘}”></div>  

And Ouput will be

Directives

Example of Custom Attribute Directive ( Highlighter )

First we need to add directive with the following command:

cmd > ng g d highlighterdirective

Which will create basic directive for us.

Directives

Change the directive with the following code:

  1. import {  
  2.     Directive,  
  3.     HostBinding,  
  4.     HostListener,  
  5.     Input,  
  6.     OnInit  
  7. } from '@angular/core';  
  8. @Directive({  
  9.     selector: '[apphighlighter]'  
  10. })  
  11. export class HighlighterDirective {  
  12.     private backgroundColor: string;  
  13.     @Input() defaultColor = 'white';  
  14.     @Input('apphighlighter') highlightColor = 'green';  
  15.     constructor() {}  
  16.     ngOnInit() {  
  17.         this.backgroundColor = this.defaultColor;  
  18.     }  
  19.     @HostListener('mouseenter') mouseover() {  
  20.         this.backgroundColor = this.highlightColor;  
  21.     }  
  22.     @HostListener('mouseleave') mouseleave() {  
  23.         this.backgroundColor = this.defaultColor;  
  24.     }  
  25.     @HostBinding('style.backgroundColor') get setColor() {  
  26.         return this.backgroundColor;  
  27.     }  
  28. }  
So in the above example we need to focus on certain things which are mentioned below:

 

  1. Import HostListener,HostBinding,Input and OnInIt from @angular/core.
  2. We had created properties defaultColor and highlightColor with the help of @ Input that means it can be set from outside also so that it can be used in any component.

Now we need to declare the Directives to app.module

First we need to import the directives to app.module.ts

  1. import {  
  2.     HighlighterDirective  
  3. } from './highlighter.directive';  
  4. then In app.module.ts we need to declare it in declaration array  
  5. @NgModule({  
  6.             declarations: [  
  7.                 AppComponent,  
  8.                 HighlighterDirective  
  9.             ],  
  10.             now we can use it on our.html page like this < h2 > Custom Attribute Directives < /h2> < div[apphighlighter] = ”’blue’”[defaultColor] = ”‘red‘“ > Some Text < /div>  
Structural Directives

They interact with the current view Container and change the structure of the DOM/HTML code. They are named structural directives because they change the structure of the DOM. For Example ( *ngIf,*ngFor,*ngSwitch).

All structural directives are prefix with *
All structural directives are prefix with *

 

  • *ngIf
    1. <h1>Structural Directives</h1>  
    2. <h2>*ngIf</h2>  
    3. <div *ngIf=”switch”>Conditional Text</div> <button (click)=”onSwitch()”>Switch</button>  

In Your .ts file

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-tasks',  
  7.     templateUrl: './tasks.component.html',  
  8.     styleUrls: ['./tasks.component.css']  
  9. })  
  10. export class TasksComponent implements OnInit {  
  11.     private  
  12.     switch = true;  
  13.     onSwitch() {  
  14.         this.switch = !this.switch;  
  15.     }  
  16. }  
in this example of *ngIf , i had created one button which acts like a toggle button. Onclik it will hide the content and vice a versa.

Directives

On Click it will remove the conditional text div

Directives

 

  • *ngFor (Simple)
    1. <h2> *ngFor </h2>  
    2. <ul>  
    3.     <li *ngFor=”let item of items”>{{item}}</li>  
    4. </ul>  

In Your .ts file

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-tasks',  
  7.     templateUrl: './tasks.component.html',  
  8.     styleUrls: ['./tasks.component.css']  
  9. })  
  10. export class TasksComponent implements OnInit {  
  11.     private items = {  
  12.         1,  
  13.         2,  
  14.         3,  
  15.         4,  
  16.         5];  
  17. }  
It will loop through the items array an bind each element with li .

 

  • *ngFor(With Index)
    1. <h2> *ngFor </h2>  
    2. <ul>  
    3.     <li *ngFor=”let item of items; let i=i ndex”>{{item}}- (Index :{{i}}) </li>  
    4. </ul>  
    Directives

It will loop through the same items array but also with the index of the elements.

Conclusion

In this post we learned about Some Directives in Angular 2, and created them. I hope you find this post useful. Thanks for reading! Cheers.

Similar Articles