Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Angular 2 form submit from component?

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().

like image 355
lock42 Avatar asked Nov 21 '17 08:11

lock42


People also ask

Which event is used to submit the form in Angular?

The ngSubmit event emits the original form submission event.

How do I access ngForm component?

In case you want to reference a directive like ngForm instead of the DOM element where the variable was declared, you simply need to set the value of the variable explicitly to the directive i.e #myForm="ngForm" . The component will be automatically added to your module by the Angular CLI.


2 Answers

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();
like image 149
Hristo Enev Avatar answered Oct 12 '22 15:10

Hristo Enev


I was trying that ngSubmit.emit() approach to update the validation state of the form fields from component, now this can be done with:

this.formGroup.markAllAsTouched();
like image 40
Yasser Nascimento Avatar answered Oct 12 '22 14:10

Yasser Nascimento