Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a angular reactive form field that uses mat-error to show validation error as soon form is loaded?

Right now it loads with a blank field and if I click in the field and click out THEN the validation error shows. But I want it to show on page load. This is the HTML

  get fcnReqDesc() { return this.fgOrderForm.get('fcnReqDesc'); }
 <mat-error *ngIf="fcnReqDesc.errors" class="error">
   <span *ngIf="fcnReqDesc.errors.required"> Requisition Description is
    <strong>required</strong></span>
 </mat-error>

and here is a version that does work but does not use mat-error

<p *ngIf="fcnReqDesc.invalid" class="error">
  <span> Requisition Description is <strong>required</strong></span>
</p>

I tried some ideas from stack overflow but they do not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 // setTimeout(() => {
    //   this.fgOrderForm.patchValue({
    //     fcnReqDesc: ''
    //   });
    // })

    // this.fgOrderForm.get('fcnReqDesc').setValidators([Validators.required]);

>Solution :

Put in ngOnInit after form group initialization markAllAsTouched

example:

this.form = this.formBulder.group({...})
this.form.markAllAsTouched()

This will mark all controls as touched and will show validation errors

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading