When building forms in Angular applications, user input validation is a common concern. However, beyond validation, a polished user experience sometimes requires auto-correcting minor issues in real time. This could be things like trimming excess whitespace, capitalizing names, or fixing common typos as the user types. To make this process scalable and reusable, you can build a custom Angular directive that automatically corrects input fields.
Why Use a Directive?
Directives in Angular are perfect for encapsulating DOM behavior. Instead of writing repetitive logic in multiple components or binding form events manually, a directive allows you to attach behavior declaratively to form inputs. This results in cleaner templates and promotes reuse across your app.
Building the Auto-Correct Directive
Let’s create a directive that attaches to any input field and modifies the value based on a simple set of rules. You can customize the logic later to fit your application’s needs.
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appAutoCorrect]'
})
export class AutoCorrectDirective {
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target.value'])
onInput(value: string): void {
const correctedValue = this.autoCorrect(value);
if (correctedValue !== value) {
this.el.nativeElement.value = correctedValue;
}
}
private autoCorrect(value: string): string {
// Example rules: trim, fix double spaces, capitalize first letter
let corrected = value.trim();
corrected = corrected.replace(/\s{2,}/g, ' ');
corrected = corrected.charAt(0).toUpperCase() + corrected.slice(1);
return corrected;
}
}
Importing the Directive
Don’t forget to import the directive in the component!
app.ts
import { Component } from '@angular/core';
import { AutoCorrectDirective } from './auto-correct';
@Component({
selector: 'app-root',
imports: [AutoCorrectDirective],
templateUrl: './app.html',
styleUrl: './app.css'
})
export class App {
}
Using the Directive
To use this directive, simply attach it to any <input> element:
<input type="text" appAutoCorrect />
This input will now automatically correct spacing issues and ensure the first letter is capitalized while the user types.
Here is the result:

Extending the Logic
The beauty of this approach is how easily it can be extended. You might add:
- Email format correction (
@gamil.comto@gmail.com) - Title case transformation
- Stripping unwanted characters (like emojis or special symbols)
You could also make the directive configurable by passing in options or a function via an @Input.
Final Thoughts
Creating an Angular directive for auto-correction adds polish and consistency to your forms without bloating your components. It’s a great example of how Angular’s architecture can help you encapsulate and scale UI behaviors in a maintainable way.
Let the directive do the correcting while your forms stay clean and user-friendly.
