Home > Enterprise >  How do I make a angular reactive form field that uses mat-error to show validation error as soon for
How do I make a angular reactive form field that uses mat-error to show validation error as soon for

Time:01-07

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" >
   <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" >
  <span> Requisition Description is <strong>required</strong></span>
</p>

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

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

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

CodePudding user response:

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

  •  Tags:  
  • Related