2
votes

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>
2
hmm strange, so I guess the best way to go about this then is to just declare my own 'submitted` variable and manage its state? - RDNotorious
im sorry i misunderstand your question.But it will work using template reference variable in reactive forms.Did you try to check if its working ? - M A Salman

2 Answers

4
votes

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>
1
votes

try like this way. You can access submitted status in template as below

<form [formGroup]="myForm" #formDir="ngForm" (ngSubmit)="doSomething()">
    <input formControlName="myInput">
    <p *ngIf="formDir.submitted">Form submitted</p>
    <button type="submit">Submit</button>
</form>

stackblitz link: https://stackblitz.com/edit/angular-hmppqf