Skip to content

Instantly share code, notes, and snippets.

@tw3
Created February 9, 2024 17:33
Show Gist options
  • Save tw3/a747789cc124a8a52f0cb17eaad8a3a9 to your computer and use it in GitHub Desktop.
Save tw3/a747789cc124a8a52f0cb17eaad8a3a9 to your computer and use it in GitHub Desktop.
Trims text for an Angular form control as the text is input
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