Skip to main content

Angular Directives

Word Direcitve means something that serves to direct or guide towards an action or goal. The purpose of Directives is similar in Angular too. Directives are basically markers for DOM elements and are used to either create new HTML elements or extend behavior of already present elements.

There are three types of Directives


  • Component Directive
  • Strucutral Directive
  • Attribute Directive

To create a directive in Angular2, you have to follow these steps

  1. Create a regular javascript class and decorate it with @Directive decorator

    import {Directive} from '@angular/core';
    
    @Directive({
        selector: "[disableOnClick]",
    })
    class DisableOnClick {
        @HostListener('click', ['$event.target'])
        onClick(element) {
            element.disabled= "disabled"
        }
    }
  2. Declare it in your module declaraion file e.g app.module.ts

    import { NgModule } from '@angular/core';
    import { DisbaleOnClick } from './components/disableOnClick.directive'
    @NgModule({
        declarations: [DisableOnClick]
    })
    class AppModule{ }
    
  3.  Use it anywhere in your HTML

    <button disableOnClick > Disable Me </button>

Now lets talk about three types of directives.

Component

Components basically extend your applications HTML vocabulary by creating new reusable elements throughout the application

Structural Directive

These directives shape your application's DOM structure by adding, removing or manipulating elements. There are number of structural directives provided by angular's rich library of items. They are easy to recognize as you will see an * in front of the name for example *ngFor, *ngIf

ngIf is a condition which add the elements into DOM when a specific condition is met.
ngFor provides iteration right into your HTML template and tell angular to add elements for the given number of times. 

Other examples are *ngSwtich

Another important point to note about structural directives is that angular internally translates them into an ng-template directive and replaces the host element with ng-template.

Also remember you cannot put more then one sturctural directives on one host element, e.g you cannot have ngFor and ngIf both on the same host element. 

Attribute Directive

Attribute Directive alters the appearance or behavior of an existing elements by extending their attribute set. NgStyle and NgModel are the most commonly used attribute directives. The example source code above also creates an attribute directive. 


Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Difference between ng-template, ng-content and ng-container

While working on a very complex feature for a client in which I had to present hierarchical dynamic data in three column layout with ability to expand like google image search on each level, I came across ng-content, which seemed like a perfect fit for the solution I was thinking about implementing. But I got confused between ng-content and ng-container when I saw the generated html while debugging my code in developer console. I further investigated both ng-content and ng-container and decided to write my finding here in my blog for future references. If you are also wondering what are they for, read on. <ng-container> When you have to write different host elements to combine many structural component like the following <div *ngIf="condition"> <div *ngFor="..."> Some content here </div> </div> You get many unintentional host elements which are not required for your layout. It becomes a prolem when you have complex appl...

Grouping Exports in Javascript code

As a Javascript developer, you will come across many occassions when you will have to export many functions, variables or other items from one file and import them in different files. You may end up with a code like the following export const function1 = () => { /*something here */ } ; export const function2 = () => { /*something here */ } ; export const function3 = () => { /*something here */ } ; export const function4 = () => { /*something here */ } ; export const function5 = () => { /*something here */ } ; export const function6 = () => { /*something here */ } ; export const function7 = () => { /*something here */ } ; And in the file you want to import you will be importing like the following import { function1, function2, function3, function5, function6, function7 } from './path_to_the_script' You can improve it using * if you want to import all the functions. import * as Functions from './path_to_the_script' This is a better way of imp...