Created
September 1, 2020 12:52
-
-
Save rajaramtt/33e5c8e9968e560610d1468a54708cc1 to your computer and use it in GitHub Desktop.
Angular Input Trim Directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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