如何触发从组件提交的 Angular 2 表单? [英] How to trigger Angular 2 form submit from component?

查看:25
本文介绍了如何触发从组件提交的 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 有属性 ngSubmitEventEmitter.因此,在组件的这个属性上执行 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆