javascript - 如何拦截提交表单?

标签 javascript angular

我的项目有以下 react 形式:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div class="line">
    <input class="title" id="title" placeholder="Заголовок вопроса" type="text" formControlName="title">
  </div>

  <div class="line">
    <textarea class="question" name="question" id="question" placeholder="Текст вопроса" formControlName="question" cols="30" rows="10"></textarea>
  </div>

  <div class="line">
    <div class="tags">
      <span class="title">Метки</span>
      <span class="tag" *ngFor="let tag of tags">{{ tag }} <span class="delete" (click)="deleteTag(tag)">X</span></span>
    </div>
    <input class="tag" id="tag" placeholder="Введите тег и нажмите enter" type="text" formControlName="tag" #tag (keyup.enter)="addTag($event, tag.value)">
  </div>

  <div class="line">
    <button class="btn btn-common" type="submit" mat-button [disabled]="form.invalid">
      Отправить
    </button>
  </div>
</form>

此表单在组件中初始化:

private form: FormGroup;
  ngOnInit() {
    this.form = new FormGroup({
      'title':      new FormControl('', [Validators.required, Validators.minLength(1)]),
      'question':   new FormControl('', [Validators.required, Validators.minLength(3)]),
      'tag':        new FormControl()
    });
  }

在#tag 字段中,用户写入标记名并按Enter 键。表格是提交的。但我需要在按 Enter 键后取消表单提交。

我的尝试:

  private addTag(event, tag): void {
    console.log(event);
    event.preventDefault();
    event.stopPropagation();

    if(!tag.trim().length) { return; }

    this.form.patchValue({tag: ''});

    if(this.tags.indexOf(tag) === -1) {
      this.tags.push(tag.trim());
    }
  }

但这并没有停止提交表单。我需要在按回车键后取消提交表单

最佳答案

keyup 事件来不及捕获提交。

我会处理 keydown 事件:

html

(keydown.enter)="addTag($event, tag.value)"

ts

private addTag(event, tag): void {
  event.preventDefault();
}

或者你可以返回false

html

(keydown.enter)="!!addTag(tag.value)"
                ^^^^
            convert to boolean

ts

addTag(tag): void {
  if(!tag.trim().length) { return; }

  this.form.patchValue({tag: ''});

  if(this.tags.indexOf(tag) === -1) {
    this.tags.push(tag.trim());
  }
}

Example

关于javascript - 如何拦截提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040023/

相关文章:

javascript - tslint 创建错误,但功能方面它工作正常

jquery - 显示侧栏菜单在页面加载时默认打开,并在单击 Angular 4 中的切换按钮时关闭

javascript - 样式化包含模板文字的附加文本

javascript - jQuery 中的 resize() 高度不会改变

javascript - 没有平台提供商

Angular2 - 具有登录和记住用户功能的应用程序

angular - 如何将 webrtc 适配器 js 包含到 Angular5 应用程序中

javascript - JS/lodash : Mutate and return data in one line of code

javascript - 限制文本区域中的字符,如何考虑回车?

javascript - 如何根据JavaScript中字符的位置提取子字符串?