Custom Directive In Angular -Sagar Jaybhay

Directive In Angular By Sagar Jaybhay

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.

To create custom directive we use below ng-cli commands to generate this.

D:\Target Dec-2019\Angular_Application\hello-sagar-jaybhay>ng g d format-input
CREATE src/app/format-input.directive.spec.ts (245 bytes)
CREATE src/app/format-input.directive.ts (151 bytes)
UPDATE src/app/app.module.ts (1095 bytes)

In the above 2 files are created and one is modified. The app.module is modified and placed the entry in app.module.ts file.

For directive, we need to import Directive from.

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

when we create the directive below is the file generated.

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

@Directive({
  selector: '[appFormatInput]'
})
export class FormatInputDirective {
  constructor() { }
}

Like component in, we decorate the class with @component directive in directive we decorate the class with @Directive({}). But only catch here the selector has the square bracket. If you see closely the selector has app is prefix for name will not crash with inbuilt directive.

Now we want to achieve functionality when we put uppercase text it will convert it into lowercase.

So for that, we add one input field in app.component.html and apply the directive to that input tag like below.

span>
    Enter Name
</span>
<input type="text" appFormatInput>

So if you see our custom directive which looks like below and in this we Listener to trigger the focus and blur event.

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

@Directive({
  selector: '[appFormatInput]'
})
export class FormatInputDirective {

  constructor(private element:ElementRef) { }
  
  @HostListener('focus') OnFocus(){
    console.log("On focus method.");
  }

  @HostListener('blur') OnBlur(){
    let value:string=this.element.nativeElement.value;
    this.element.nativeElement.value=value.toLowerCase();
    console.log("On Blur method.");
  }  
}

In the above example, we use ElementRef this for accessing native DOM element from code directly. A wrapper around a native element inside of a View. Angular say try to avoid using this instead you can use interpolation. When we apply directive we need to use like attribute inside that Html tag element.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *