Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Created September 1, 2020 12:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajaramtt/33e5c8e9968e560610d1468a54708cc1 to your computer and use it in GitHub Desktop.
Save rajaramtt/33e5c8e9968e560610d1468a54708cc1 to your computer and use it in GitHub Desktop.
Angular Input Trim Directive
import { Directive, HostListener, OnInit, Optional } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
// tslint:disable-next-line:directive-selector
selector: 'input[trimInput],textarea[trimInput]',
})
export class TrimInputDirective implements OnInit {
constructor(@Optional() private ngControl: NgControl) {
}
ngOnInit(): void {
if (!this.ngControl) {
console.warn('TrimInputDirective required ngModel, formControl or formControlName.');
return;
}
}
@HostListener('blur', [
'$event.target',
'$event.target.value',
])
onBlur(el: any, value: string): void {
if ('function' === typeof value.trim && value.trim() !== value) {
el.value = value.trim();
const event = document.createEvent('Event');
event.initEvent('input', false, false);
el.dispatchEvent(event);
const eventNew = document.createEvent('Event');
eventNew.initEvent('blur', false, false);
el.dispatchEvent(eventNew);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment