javascript - Angular 表单 - 如何在表单无效时禁用 onSubmit 事件?

标签 javascript angular forms typescript

<div>
  <form (ngSubmit)="mySubmit()" #msgBoxForm="ngForm">
    <button mat-raised-button color="accent" (click)="rollDice()">
      RollDice
    </button>
    <input
      type="text"
      name="msgInputBox"
      [(ngModel)]="TextMessage"
      required
      #box (keyup.enter)="enterSubmit()"
      placeholder="Message" >
    <button
      type="submit"
      class="btn btn-success"
      [disabled]="!msgBoxForm.form.valid">
      Submit
    </button>
  </form>
</div>

现在当输入框为空时,虽然提交按钮将被禁用,但按回车键将同时调用 enterSubmit() 和 mySubmit() 方法。即使单击没有“提交”类型的 RollDice 按钮,也会调用 mySubmit()。如何仅在单击提交按钮时调用 mySubmit()?

最佳答案

表单内的任何按钮或 enter press 的默认行为都是提交表单。为防止这种情况,您可以执行以下操作:

<div>
  <form (ngSubmit)="msgBoxForm.form.valid && mySubmit()" #msgBoxForm="ngForm">
    <button mat-raised-button color="accent" (click)="rollDice($event)">
      RollDice
    </button>
    <input
      type="text"
      name="msgInputBox"
      [(ngModel)]="TextMessage"
      required
      #box (keyup.enter)="enterSubmit($event)"
      placeholder="Message" >
    <button
      type="submit"
      class="btn btn-success"
      [disabled]="!msgBoxForm.form.valid">
      Submit
    </button>
  </form>
</div>

在你的 typescript 中:

rollDice(event: Event) {
  event.preventDefault();
  //rest of your code
}

enterSubmit(event: Event) {
  event.preventDefault();
  //rest of your code
}

这允许您仅通过单击提交按钮来提交表单。

编辑:我添加了如何在提交表单之前检查表单有效性。解决方案来自这里:source

关于javascript - Angular 表单 - 如何在表单无效时禁用 onSubmit 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342769/

相关文章:

php - 找不到对象!在此服务器上找不到请求的 URL。未访问 PHP 文件

php - 如何将 HTML 表单的多个选定选项分配给 PHP 变量?

JavaScript:整数数组,对每个元素求和整数

javascript - 无法在 REST API 之外使用 Mongoose 查询 MongoDB

javascript - 使用Codeigniter,如何使用get_where,但不包含某些行?

javascript - 使用对象数组动态生成新数组

javascript - 如何通过JavaScript在textarea onclick上发出control-c/command-c?

Angular 2 Reactive form Validator - 如何允许null,但是当有输入时,输入需要是数字?

javascript - typescript 中服务的动态函数调用

php - 使用 php 从具有相同表的同一服务器查找 2 个 mysql 数据库中的差异