DEV Community

Cover image for Remove Unwanted Spaces from Angular Form Submission
nightwolfdev
nightwolfdev

Posted on • Originally published at nightwolf.dev

1

Remove Unwanted Spaces from Angular Form Submission

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();
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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) { }
Enter fullscreen mode Exit fullscreen mode

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() {

}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
  }

}
Enter fullscreen mode Exit fullscreen mode

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 { }
Enter fullscreen mode Exit fullscreen mode

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 { }
Enter fullscreen mode Exit fullscreen mode

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" />
Enter fullscreen mode Exit fullscreen mode

Visit our website at https://nightwolf.dev and follow us on Twitter!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay