Explore Directives In Angular2

Directives are just instruction,

Like components ,selectors of html tags  which tells angular 2 what to do at certain places of your code.Directives are key part which not only allows to render views with help of components but also allows  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.

screenshot-46

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

Screenshot (49).png

Attribute Directives:

they interact with the element to which they are applied to.(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 follow

  • ngClass

First crate one component using angular-cli. which will create boiler plate for us.for example if we are creating 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.

.border{
        border: 3px solid blue;
}
.background{
        background-color: green;
}
div {
        width: 100px;
        height: 100px;
}

then in .html file write these.

<h1>Attribute Directives</h1>
<h2>ngClass/ngStyle</h2>
<div [ngClass]="{border: false, background: true}" ></div>

you will get this output on running

screenshot-52

  • ngStyle
<h1>Attribute Directives</h1>
<h2>ngClass/ngStyle</h2>
<div [ngStyle]="{‘background-color’: ‘red‘}"></div>

screenshot-59

Example of Custom Attribute Directive ( Highlighter ) :

first we need to add directive with following command:

cmd > ng g d highlighterdirective

which will create basic directive for us.

Screenshot (62).png

change the directive with following code


import { Directive,HostBinding,HostListener,Input,OnInit } from '@angular/core';

@Directive({

selector: '[apphighlighter]'

})

export class HighlighterDirective {

private backgroundColor:string;

@Input() defaultColor='white';

@Input('apphighlighter') highlightColor='green';

constructor() { }

ngOnInit(){

this.backgroundColor=this.defaultColor;

}

@HostListener('mouseenter') mouseover(){

this.backgroundColor=this.highlightColor;

}

@HostListener('mouseleave') mouseleave(){

this.backgroundColor=this.defaultColor;

}

@HostBinding('style.backgroundColor') get setColor(){

return this.backgroundColor;

}

}

so in 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

import { HighlighterDirective } from ‘./highlighter.directive’;

then In app.module.ts we need to declare it in declaration array

@NgModule({

  declarations: [

    AppComponent,

HighlighterDirective

  ],

Screenshot (65).png

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 *
  • *ngIf
<h1>Structural Directives</h1>
<h2>*ngIf</h2>
<div *ngIf=”switch”>Conditional Text</div>
<button (click)=”onSwitch()”>Switch</button>


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

@Component({

selector: 'app-tasks',

templateUrl: './tasks.component.html',

styleUrls: ['./tasks.component.css']

})

export class TasksComponent implements OnInit {

private switch=true;

onSwitch(){

this.switch=!this.switch;

}

}

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.

 

Screenshot (74).png

on Click it will remove the conditional text div

Screenshot (76).png

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

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

@Component({

selector: 'app-tasks',

templateUrl: './tasks.component.html',

styleUrls: ['./tasks.component.css']

})

export class TasksComponent implements OnInit {

private items={1, 2, 3, 4, 5];

}

 

it will loop through the items array an bind each element with li.

  • *ngFor(With Index)
<h2> *ngFor</h2>
<ul>
	<li *ngFor=”let item of items; let i = index” >{{item}}- (Index :{{i}})</li>
</ul>

Screenshot (79).png

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

Conclusion

So, With the help of this blog, we learned about Some Directives in Angular 2, and created them. I hope you find this post useful.In next article i will show , how to create custom directive for drop down control. Thanks for reading !cheers!!!!!!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s