When a user types a value into a form field, it’s a very common mistake to add spaces at the beginning and/or end of the value. We can clean those unwanted spaces up very easily using an Angular directive!
Trim Values Manually
When an Angular form is submitted, you can get all the values of the form and then use the Javascript trim method to remove unwanted spaces from each property.
const data = this.form.value;
data.firstName = data.firstName.trim();
Doesn’t look too difficult, but imagine if there are more fields. Instead of adding more code to the form submission logic, we can use a directive to make things easier!
Trim Directive
Let’s start by importing what we need to create the directive.
import { Directive, ElementRef, HostListener } from '@angular/core';
Within the directive’s constructor, create a parameter called element with the type ElementRef. This will be a reference to the host element, which is the form field the directive is added to.
constructor(private element: ElementRef) { }
We don’t want to remove spaces while the user is typing. Instead, let’s remove spaces once the form field loses focus. We can listen for the blur event using a HostListener.
@HostListener('blur') onBlur() {
}
Get the current value of the form field from its native element, trim any beginning and ending spaces, and then apply the cleaned up value to the form field.
const value = this.element.nativeElement.value;
this.element.nativeElement.value = value.trim();
Here’s the final code:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appTrim]'
})
export class TrimDirective {
constructor(private element: ElementRef) { }
@HostListener('blur') onBlur() {
const value = this.element.nativeElement.value;
this.element.nativeElement.value = value.trim();
}
}
To make this directive usable across any module, let’s create it as its own module so it can be imported into any module where it’s needed.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TrimDirective } from './trim.directive';
@NgModule({
declarations: [TrimDirective],
exports: [TrimDirective],
imports: [CommonModule]
})
export class TrimModule { }
To use the directive, first import it into the module where you want to use it.
import { TrimModule } from 'path/to/trim.module';
@NgModule({
...
imports: [
...
TrimModule,
...
]
})
export class ContactFormModule { }
You can now add the directive attribute, which is called appTrim, to the form fields!
<input appTrim type="text" id="firstName" name="firstName" formControlName="firstName" />
Visit our website at https://nightwolf.dev and follow us on Twitter!