Angular submit outside form

Asked by At

I need to invoke submit on form(s) when clicking on button outside the form as well as changing FormGroupDirective.submitted to true.

I have next layout

<form (ngSubmit)="submit()" #myForm [formGroup]="formGroup">
...
</form>

<button (click)="formGroupDirective.ngSubmit.emit()" *ngIf="showEditControl"
    class="btn btn_blue mr-3 button-save" type="submit">
    {{'buttons.save' | translate}}
</button>

And component.ts

@ViewChild('myForm', {read: FormGroupDirective}) formGroupDirective: FormGroupDirective;

This does invoke (ngSumit) however the property submitted is not changed. It's not good to change the property itself as submitted is readonly. What could be done here (except for creating hidden submit buttons and emulating click on them)?

1 Answers

0
Sadid Khan On

use this.

in html:

<form [formGroup]="form" #myForm="ngForm">
    // ...Form Controls
</form>

<button (click)="submitForm()" *ngIf="showEditControl" class="btn btn_blue mr-3 button-save" type="submit">
    {{'buttons.save' | translate}}
</button>

and in component.ts

@ViewChild('myForm') form: FormGroupDirective;

formGroup: FormGroup = new FormGroup({
    myInput: new FormControl(''),
    //etc...
});

submitForm() {
    this.form.onSubmit(undefined);
}