4

I have a simple form:

this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});

When user paste something into the input I reformat values using regex and update the form.

onPaste(event) {
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
    // this.ref.detectChanges();
  }

But when I paste something, for example

325435956
325435956

It duplicate it and as a result I see 325435956, 325435956 325435956 325435956 but I expect to see 325435956, 325435956. Where is my mistake and how to fix that?

Working example you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

1
  • have this line this.searchForm.setValue({value:''}) in the onPaste method and try once. This will clear the form value whenever we are pasting, I guess the value is retained in the object Commented Dec 8, 2017 at 10:10

1 Answer 1

6

Even though you handle the paste function, the default behavior is left unchanged.

So, it first handles the method and prints out the expected values. And then pastes the values as is.

You should prevent the default behavior.

onPaste(event) {
    event.preventDefault();

    //rest of the method as it is right now
}

Fixed example: https://stackblitz.com/edit/angular-7orqb9?file=app/hello.component.ts

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.