I am trying to trim a text input but it is duplicating the value
I am new to angular can you please help me out finding the solution StackBlitz Code
preventDefault()
Usage:
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
The problem was here, that you are trying to stop the pasting behavior.
if (!Number(event)) {
e.preventDefault();
}
Scenarios:
Scenario 1: Pasted value is not a number
Scenario 2: Pasted value is a number
<input>
element.I believe what you try to achieve:
Blocking the default pasting behavior.
Only allow the number to be pasted. When the value is not a number, it will exit the function.
if (!Number(event)) return;
The complete code of the "paste" listener should be as below:
@HostListener('paste', ['$event']) onPaste(e: ClipboardEvent) {
e.preventDefault();
let event = e.clipboardData.getData('text');
let reg = new RegExp(/\s/g);
//allow paste only number values
if (!Number(event)) return;
if (reg.test(event)) {
console.log('Dir "' + event + '"');
this.eleRef.nativeElement.value = event.trim();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.