如何在输入时阻止表单提交

时间:2016-02-14 19:27:56

标签: javascript forms angular

我有一个表单,我有一个名为systemParameters的字段,我想指定许多值,按Enter键保存在数组中。

问题是在按下输入表格时同时提交。

在这种情况下哪种方式最好提交表单?

我最初的想法是禁用提交按钮,直到所有字段都已满,但是当我填写所有字段时,因为我向systemParameters字段添加了几个值,这将导致表单在某个时刻提交。

这是我迄今所做的一切。

https://plnkr.co/edit/dHJf8QEhhvU5LupdDcmX?p=info

import {Component} from "angular2/core";
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, AbstractControl, Validators, Control} from "angular2/common";

@Component({
    selector: 'parameters-form',
    directives: [FORM_DIRECTIVES],
    template: `
      <h1>Parameters Form</h1>
      <p>{{ arr }}</p>
      <form [ngFormModel]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="ui form">

        ...

          <div class="field">
            <label for="systemParameters">System Parameters</label>
            <input type="number"
                   id="systemParameters"
                   placeholder="systemParameters Param"
                   [ngFormControl]="systemParameters"
                   (keypress)="addToArray($event, systemParameters.value)">

            <button type="button" (click)="addToArray(systemParameters.value)">Add</button>

          </div>

          ...

        <button type="submit" class="ui button">Submit</button>
      </form>
    `
})
export class ParametersForm {
  myForm: ControlGroup;
  systemParameters: AbstractControl;
  arr: number[];

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      "realisations" : [""],
      "numConstSteps" : [""],
      "timeHorizon": [""],
      "continuationStep" : [""],
      "continuationStepSign" : [""],
      "numberOfModelParameters" : [""],
      "systemParameters" : [],
      "param" : [""],
      "netLogoFile" : [""],
      "numberOfModelVariables" : [""],
      "restrictOperator" : [""],
      "liftOperator" : [""],
      "xInitial" : [""]

    });
    this.arr = [];
    this.systemParameters = this.myForm.controls["systemParameters"];
  }
  addToArray(event,value: any): void {
    if (event.charCode == 13){
      this.arr.push(value);
      this.arr = this.arr.slice();
      (<Control>this.systemParameters).updateValue("");
    }
  }
  onSubmit(form: any): void {
    console.log(this.arr);
    form.systemParameters = this.arr;
    console.log("your submitted value:", form)
  }

}

1 个答案:

答案 0 :(得分:0)

我不确定这是一个聪明的解决方案,但似乎有效

<form #f=ngForm [ngFormModel]="myForm" (keydown.enter)="false" (ngSubmit)="onSubmit(myForm.value)" class="ui form">
  ...  
<button type="button" (click)="f.ngSubmit.emit(null)" class="ui button">Submit</button>

另请参阅https://plnkr.co/edit/sekWZHOXlyQOSMoRuAUz?p=preview(从模板中删除一点)