To create an Angular directive that restricts user input according to custom conditions, follow this comprehensive approach:
Basic Directive Structure
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appInputRestrictor]'
})
export class InputRestrictorDirective {
@Input() appInputRestrictor: string | RegExp; // Can be regex pattern or validation type
constructor(private el: ElementRef) {}
@HostListener('input', ['$event']) onInputChange(event: Event) {
const input = event.target as HTMLInputElement;
const initialValue = input.value;
const regex = this.getValidationPattern();
if (regex) {
input.value = initialValue.replace(regex, '');
if (initialValue !== input.value) {
event.stopPropagation();
}
}
}
private getValidationPattern(): RegExp | null {
if (typeof this.appInputRestrictor === 'string') {
return this.getPredefinedPattern(this.appInputRestrictor);
}
return this.appInputRestrictor;
}
private getPredefinedPattern(type: string): RegExp | null {
const patterns = {
'numbers-only': /[^0-9]/g,
'letters-only': /[^a-zA-Z]/g,
'alphanumeric': /[^a-zA-Z0-9]/g,
'no-special-chars': /[^\w\s]/g
};
return patterns[type] || null;
}
}