如何拦截提交表格?

时间:2017-12-31 04:35:53

标签: javascript angular

我的项目遵循反应形式:

<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 user中写入tagname并按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());
    }
  }

但这并不止于提交表格。按Enter键

后需要取消提交表格

1 个答案:

答案 0 :(得分:1)

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