Angular 5 表单重复输入值

Angular 5 form duplicates input value

我有一个简单的表格:

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

当用户将内容粘贴到输入中时,我使用正则表达式重新格式化值并更新表单。

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();
  }

但是当我粘贴一些东西时,例如

325435956
325435956

它复制了它,结果我看到了 325435956, 325435956 325435956 325435956,但我希望看到 325435956, 325435956。我的错误在哪里以及如何解决?

您可以在此处找到工作示例 https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

即使您处理了粘贴功能,默认行为仍保持不变。

因此,它首先处理该方法并打印出预期值。然后按原样粘贴值。

您应该防止默认行为。

onPaste(event) {
    event.preventDefault();

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

固定示例:https://stackblitz.com/edit/angular-7orqb9?file=app/hello.component.ts