简体   繁体   English

角度6:组件内的表单,单击“提交”按钮时未触发ngSubmit

[英]Angular 6: Form inside a component, ngSubmit not triggered when clicking on submit button

I have a shared component and inside the component, I have created a reactive form, a bunch of form fields and two buttons. 我有一个共享的组件,并且在组件内部,我创建了一个反应式表单,一堆表单域和两个按钮。

<form [formGroup]="formGroup" (ngSubmit)="onFormSubmit()">
  <div class="form-content">
    <div class="form-item" *ngFor="let field of fieldTypes">
      <div class="field-label">
        <label>{{ field.label }}:</label>
      </div>
      <div class="input-field">
        <input [type]="field.type" [formControlName]="field.name" [readonly]="field.readonly" [ngClass]="{'readonly': field.readonly}">
      </div>
      <span *ngIf="field.mandatory">*</span>
    </div>
  </div>
  <div class="form-button-group">
    <button type="submit" [disabled]="!formGroup.valid">Save</button>
    <button type="reset">Cancel</button>
  </div>
</form>

When I use the shared component in a page and click submit button, nothing happens. 当我在页面中使用共享组件并单击提交按钮时,没有任何反应。 The ngSubmit event is never triggered. 永远不会触发ngSubmit事件。 I will have to add (click) on the button to force calling the method. 我将不得不在按钮上添加(单击)以强制调用该方法。

<button type="submit" [disabled]="!formGroup.valid" (click)="onFormSubmit()">Save</button>

Any ideas? 有任何想法吗? Any help will be appreciated! 任何帮助将不胜感激!

Issue is not related to the above code. 问题与以上代码无关。 Might be, you have any other form in the DOM. 可能是,您在DOM中具有任何其他形式。 Here is the stackblitz version of your code that works perfectly. 这是完美工作的代码的stackblitz版本。

https://stackblitz.com/edit/angular-qyj4uq https://stackblitz.com/edit/angular-qyj4uq

I think your form is not valid and that's why it's not being submitted. 我认为您的表格无效,因此未提交。 Replace the way you're validating your form: 替换您验证表单的方式:

<form [formGroup]="formGroup" (ngSubmit)="onFormSubmit()" #myForm="ngForm">
  <div class="form-content">
    ....
  </div>
  <div class="form-button-group">
    <button type="submit" [disabled]="!myForm.form.valid">Save</button>
    ....
  </div>
</form>

In your component check the value of myForm.form.errors - That should give you a hint. 在您的组件中检查myForm.form.errors的值-这应该给您一个提示。

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

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