i need a solution, in the form of some directive or maybe you know what, to prevent the user from hitting a lot of spaces.
I am try with this link solutions:
https://www.titanwolf.org/Network/q/77d56d42-68ae-4a29-b239-0145da1c6852/y
But without success for my use case.
This is good solution but no work on my case:
import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
control.setValue('');
}
return null;
}
I need to prevent to user can hitting space few times.. Example imagine input type text and i try to set John ________ John-TEST ________ TEst
___ is just space on keyboard...
I need to prevent it. Maybe directive ?
do you know the solution or the link to a solution?
CodePudding user response:
You can use a directive with @HostListener to listen for space-key and combine it with ElementRef or Input to check the input text-value, so if last character is space, prevent event.
@HostListener('keydown.space', ['$event']) handler(event: KeyboardEvent) {
console.log(event);
if (this.input.endsWith(' ')) {
event.preventDefault();
}
}
** You can also remove .space and check the char in the event to see if space and then handle it.
CodePudding user response:
You can get your desired result by using the rxjs operators(debounceTime, distinctUntilChanged);
this.searchField.valueChanges
.pipe(debounceTime(800), distinctUntilChanged())
.subscribe((x) => console.log(x));
}
CodePudding user response:
This can be achieved in simple HTML and JS as well. Or you can convert this to a JS logic
Here is sample html code for an input element
To alert user on entering multiple spaces:
<input oninput="javascript: if (this.value.match(/ /g)) window.alert('Multiple Spaces Entered');">
Reduces multiple spaces to one single space immediately:
<input oninput="javascript: if (this.value.match(/ /g)) this.value = this.value.replace(/ /g, ' ');">
CodePudding user response:
Try this to replace multiple spaces with a single space.
ngOnInit(): void {
this.control.valueChanges.subscribe((str: string) => {
const newVal = str.replace( / /g, ' ' )
this.control.setValue(newVal, {emitEvent: false});
})
or you can create without-space directive:
export class WithoutSpacesDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const newVal = input.value.replace( / /g, ' ' )
input.value = newVal;
}
}
html:
<input type="text" without-spaces [formControl]="control" />
https://stackblitz.com/edit/angular-ivy-gxkr5a?file=src/app/app.component.ts
