rel1x
rel1x

Reputation: 2441

Angular 5 form duplicates input value

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

Upvotes: 4

Views: 1463

Answers (1)

nipuna-g
nipuna-g

Reputation: 6652

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

Upvotes: 6

Related Questions