Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive Forms submitted state

I was wondering if there was any way to retrieve the 'submitted' state of a Reactive Form.

With template driven forms you can access the FormGroupDirective via the 'ngForm' as follows

<form #form='ngForm' (ngOnSubmit)="handleSubmit()">
    <p *ngIf="form.invalid && form.submitted">Invalid</p>
    <button type="submit">Submit</button>
</form>

But when using reactive forms I am unable to achieve the same functionality without declaring my own variable that I update/reset on submit which seems weird since this isn't needed in the template driven variant.

What I've tried so far:

  • (in component) @ViewChild(FormGroupDirective) formGroupDirective / (in template) formGroupDirective.submitted
    • ExpressionChangedAfterItHasBeenCheckedError
  • form="ngForm" [formGroup]="myForm"
    • There are multiple directives with 'exportAs' set to 'ngForm'

Any suggestions?

EDIT: reactive form

<form [formGroup]="myForm" (submit)="doSomething()">
    <input formControlName="myInput">
    <p *ngIf="myForm.invalid">This is visible before submitting</p>
    <button type="submit">Submit</button>
</form>
like image 310
RDNotorious Avatar asked May 15 '26 12:05

RDNotorious


1 Answers

Stackblitz: https://stackblitz.com/edit/angular-8-reactive-form-validation-vv7npe

Use template reference variable on form tag #form="ngForm"and then you can directly use *ngIf="myForm.invalid && form.submitted"

<form [formGroup]="myForm" #form="ngForm" (ngSubmit)="doSomething()">
    <input formControlName="myInput">
    <p *ngIf="myForm.invalid && form.submitted">This is visible before submitting</p>
    <button type="submit">Submit</button>
</form>
like image 163
M A Salman Avatar answered May 17 '26 01:05

M A Salman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!