I have a directive that filters text pasted into an input field. Special characters are removed and only alphanumerical chars are kept.
export class PasteFilterDirective {
constructor(private element: ElementRef) {}
@HostListener('paste', ['$event'])
handlePaste(event: ClipboardEvent) {
event.preventDefault();
const rawText = event.clipboardData?.getData('text/plain');
const parsedText = this.removeSpecialChars(rawText);
this.element.nativeElement.value = parsedText;
}
private removeSpecialChars(str: string): string {
return str.match(/[A-Za-z0-9]/g).join('');
}
}
The directive works fine, except for the fact that after pasting, NgModel is not updated. In other words - the input value changes, but if I have an ngModel binding against that input field, it won't change. Here's a stackblitz demonstrating the issue.
How can I write to the input field in a way that updates ngModel?