Custom Directives

Create a directive that convert string to lowercase

ng g d directives/input-format --skipTests true

Directive.ts

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

@Directive({
  selector: '[appInputFormat]'
})
export class InputFormatDirective {
  constructor(private el: ElementRef) { }

  @HostListener('blur') onBlur(){
    // Access the actual DOM object
    let value: string = this.el.nativeElement.value;
    console.log(value);
    this.el.nativeElement.value = value.toLowerCase();
  }
}

HTML

<input type="text" appInputFormat>

Convert string to uppercase

Directive.ts

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

@Directive({
  selector: '[appInputFormat]'
})
export class InputFormatDirective {
  @Input('format') format;

  constructor(private el: ElementRef) { }

  @HostListener('blur') onBlur(){
    let value: string = this.el.nativeElement.value;

    if(this.format == 'lowercase')
      this.el.nativeElement.value = value.toLowerCase();
    else
      this.el.nativeElement.value = value.toUpperCase();

  }
}

HTML

<input type="text" appInputFormat [format]="'uppercase'">

Cleaner method

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

@Directive({
  selector: '[appInputFormat]'
})
export class InputFormatDirective {
  @Input('appInputFormat') format;

  constructor(private el: ElementRef) { }

  @HostListener('blur') onBlur(){
    let value: string = this.el.nativeElement.value;

    if(this.format == 'lowercase')
      this.el.nativeElement.value = value.toLowerCase();
    else
      this.el.nativeElement.value = value.toUpperCase();
  }
}
<input type="text" [appInputFormat]="'uppercase'">
Was this page helpful?