How to trigger Angular 2 form submit from component?

十年热恋 提交于 2019-12-05 12:13:21

问题


Basically, I have

<form #f="ngForm" (ngSubmit)="save(f.form)" #formElement>
    ...
    <button class="btn btn-primary" #saveButton>Save</button>
</form>

I want to be able to trigger submit() from the component. I've tried @viewChild('formElement') and renderer.invokeElementMethod to trigger click().


回答1:


NgForm has property ngSubmit which is EventEmitter. So doing emit() on this property from the component will trigger a submit.

Also you need to use your f variable instead of formElement because f is referencing to ngForm.

@ViewChild('f') form: NgForm;

form.ngSubmit.emit();


来源:https://stackoverflow.com/questions/47408404/how-to-trigger-angular-2-form-submit-from-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!