Home > Enterprise >  Angular directive to handle mouse paste by cleaning string from clipboard
Angular directive to handle mouse paste by cleaning string from clipboard

Time:03-30

I'm so close.

My input is a number input, with a increment=".000001" and hiding the spin buttons.

In my directive I have:

@HostListener('paste', ['$event'])
onPaste(event: ClipboardEvent) {
    console.log('You have pasted successfully');
    const input = event.target as HTMLInputElement;
    let clipboardData = event.clipboardData;
    let pastedText = clipboardData.getData('text').toUpperCase();
    console.log("pastedText: "   pastedText);
    let trimmedText = pastedText.replace(/\s|[A-Z_]|[#$%,^&*()]/g, '');
    console.log("trimmedText: "   trimmedText);
    (event.target as HTMLInputElement).value = trimmedText;
}

if I paste, with mouse right click or ctrl v paste, the string: sd87634ee5jkbhsdf74bhgf.34iuhsdef76

event.target.value = trimmedText; console.log("trimmedText: " trimmedText); trimmedText equals 87634574.3476, so the initial string is cleaned perfectly..

but when the function is completed, it appends a messier version 87634574.347687634e5743476

What's going on here?

CodePudding user response:

you'll need to add this at the top of your function:

event.preventDefault();

to actually stop the native paste event from executing after you set the input value.

right now you're just setting a value 87634574.3476 then the paste is executing and appending the pasted value 87634e5743476 which is your pasted value without invalid number characters (yes, one e is a valid number character).

  • Related