简体   繁体   English

动态表单提交重新加载页面而不是调用 ngSubmit 函数

[英]Dynamic form submit reloads the page instead of calling ngSubmit function

I am trying to submit form dynamically from ts file.我正在尝试从 ts 文件动态提交表单。

Form形式

<form [formGroup]="mainForm" #mainFormEle (Submit)="doNothing()">
.....
</form>

and the ts和 ts

  @ViewChild('mainFormEle',{static:false}) mainFormEle

  doNothing(){
    ..
    console.log('came in')
    ..
  }

  mainFunc(){
    ..
    this.mainFormEle.nativeElement.submit()
    ..
  }

But the above block reloads the page on submit.但是上面的块在提交时重新加载页面。 And never goes into doNothing().并且永远不会进入 doNothing()。 Also tried with (ngSubmit) and (onSubmit)也尝试过 (ngSubmit) 和 (onSubmit)

It's likely that you have a button within that form.您可能在该表单中有一个button For it not to trigger the native action of submitting the form.因为它不会触发提交表单的本机操作。 You have to explicitly add `type="button" on the button.您必须在按钮上显式添加 `type="button"。

eg例如

<button type="button">
  <!-- rest of the button -->
</button>

I found the solution.我找到了解决方案。

  1. Introduced a submit button.引入了提交按钮。
  2. Instead of submitting the form from ts, Just triggered the click event on the button.不是从 ts 提交表单,而是触发了按钮上的点击事件。
<button type="submit" #submitButton></button>

or或者

<button type="submit" hidden #submitButton></button>
@ViewChild('submitButton',{static:false}) submitButton

  doNothing(){
    ..
    console.log('came in')
    ..
  }

  mainFunc(){
    ..
    this.submitButton.nativeElement.click()
    ..
  }

And now it works.现在它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM