按(单击)按钮时调用(ngSubmit)

nif*_*ody 13 typescript angular

我的Angular2表单组件上有两个按钮.按钮正在执行自己的功能.

  1. 按钮提交:哪个提交API的所有值.
  2. 按钮添加.:将对象推送到数组.

这两种方法都在这里......

onSubmit() {
this.submitted = true;
this.model.service_requests = this.modelJobServices;
this.onCreateJob();
}

addJobService(modelJobService :Jobservice){
let modelJobServiceLocal = new Jobservice(modelJobService.service_id,modelJobService.service_note,modelJobService.status)
this.modelJobServices.push(modelJobServiceLocal);
}
Run Code Online (Sandbox Code Playgroud)

我的Component.html结构如下

<form #jobRegistrationForm="ngForm" (ngSubmit)="onSubmit()">
......
......
......
<button class="flat btn-primary form-control" id="btn_add" (click)="addJobService(modelJobService)"> ADD SERVICE </button>
....
....
....
<button (submit)="onSubmit()" [disabled]="!jobRegistrationForm.form.valid" class="flat form-control col-md-4 btn-primary">{{BUTTON_TEXT}}</button>
Run Code Online (Sandbox Code Playgroud)

当我按下(click)按钮时,表单将提交给API调用.但我没有打电话onSubmit()(click)按钮事件

Gün*_*uer 40

type="submit"默认情况下,表单中的按钮.

明确地将它们设为普通按钮

<button type="button"
Run Code Online (Sandbox Code Playgroud)

  • @Zaphoid 这不是 Angular 做出的选择:除非另有说明,按钮的类型始终默认为“提交”,即使在普通 JavaScript 中也是如此。另请参阅[此 stackoverflow 线程](/sf/ask/687736591/)。我想 Angular 想要覆盖这种行为会很困难并且令人困惑。 (4认同)
  • 这太疯狂了!!:-p非常感谢!我不会猜到的。您知道为什么Angular吗?对我来说,如果只为type =“ submit”按钮调用ngSubmit,那会更干净。 (3认同)
  • 如此简单,但很难找到!谢谢你! (2认同)

aru*_*mar 7

根据 W3 规范,按钮内属性类型的默认值为“提交”。

IE<button> == <button type="submit">

如果您不希望触发 ngSubmit 事件,请将属性类型设置为按钮。

<button type="button">

或者使用 $event.preventDefault()。

<button (click)="addJobService(modelJobService); $event.preventDefault()"