简体   繁体   English

从 Angular 表单外部的按钮提交表单

[英]Submit a form from a button outside of the form in Angular

How can I submit a form in Angular (2+) programmatically from a button which resides outside of the form?如何通过位于表单外部的按钮以编程方式提交 Angular (2+) 中的表单? This should be through a click event which invokes a function in an Angular component?这应该是通过点击事件调用 Angular 组件中的函数吗?

I use the method shown here (from: How to trigger Angular 2 form submit from component? ) 我使用此处显示的方法(来自: 如何触发从组件提交Angular 2表单?

NgForm has property ngSubmit which is EventEmitter. NgForm具有属性ngSubmit,它是EventEmitter。 So doing emit() on this property from the component will trigger a submit. 因此,在组件上对此属性执行emit()将触发提交。

Also you need to use your f variable instead of formElement because f is referencing to ngForm. 另外,您还需要使用f变量而不是formElement,因为f引用了ngForm。

@ViewChild('f') form: NgForm; @ViewChild('f')形式:NgForm;

form.ngSubmit.emit(); form.ngSubmit.emit();

    **<formname>.ngSubmit.emit()** is used to submit the form when click the button from outside of the form.

For Example :    
    <form (ngSubmit)="save()" #submitForm="ngForm">
      <input type="text" name="name" required>
    </form>    
    <button (click)="submitForm.ngSubmit.emit()"
    [disabled]="!submitForm.form.valid">SAVE</button>

When click the SAVE button its call the save() function in the component.

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

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