Created
February 9, 2024 17:33
-
-
Save tw3/a747789cc124a8a52f0cb17eaad8a3a9 to your computer and use it in GitHub Desktop.
Trims text for an Angular form control as the text is input
This file contains 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 } from '@angular/core'; | |
import { NgControl } from '@angular/forms'; | |
// Trims text for an Angular form control as the text is input, e.g. " foobar " -> "foobar" | |
@Directive({ | |
selector: '[trimOnInput]', | |
standalone: true, | |
}) | |
export class TrimOnInputDirective { | |
constructor(private readonly ngControl: NgControl) {} | |
@HostListener('input') | |
onInput(): void { | |
const control = this.ngControl.control; | |
if (!control) { | |
return; // control does not exist | |
} | |
const value = control.value; | |
if (typeof value !== 'string') { | |
return; // value is not a string | |
} | |
const trimmedValue = value.trim(); | |
if (value === trimmedValue) { | |
return; // value is already trimmed | |
} | |
control.setValue(trimmedValue); | |
} | |
} | |
// Usage in Angular template: | |
// <input trimOnInput ...> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment