如何触发Angular 2表单从组件提交? [英] How to trigger Angular 2 form submit from component?
本文介绍了如何触发Angular 2表单从组件提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我有
<form #f="ngForm" (ngSubmit)="save(f.form)" #formElement>
...
<button class="btn btn-primary" #saveButton>Save</button>
</form>
我希望能够从组件触发submit()
.
我已经尝试过@viewChild('formElement')
和renderer.invokeElementMethod
来触发click()
.
I want to be able to trigger submit()
from the component.
I've tried @viewChild('formElement')
and renderer.invokeElementMethod
to trigger click()
.
推荐答案
NgForm 具有属性ngSubmit
,即 EventEmitter .因此,在组件中对该属性执行emit()
将会触发提交.
NgForm has property ngSubmit
which is EventEmitter. So doing emit()
on this property from the component will trigger a submit.
此外,您还需要使用f
变量而不是formElement
,因为f
引用了ngForm
.
Also you need to use your f
variable instead of formElement
because f
is referencing to ngForm
.
@ViewChild('f') form: NgForm;
form.ngSubmit.emit();
这篇关于如何触发Angular 2表单从组件提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文