How to trigger Angular 2 form submit from componen

2019-04-05 08:22发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-05 09:12

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();
查看更多
登录 后发表回答