Angular12 Form validator is validating on load page

Viewed 12

I already search for all community and don't find any solution.

Have a form in angular inside of stepper. The problem is when page is load, the form is validating on start, making the input in red color, like this:

Image Form

How can i prevent this? I already try with markAsPristine and others, but, nothing...

Here is .TS part when initialize the form (it's call from ngOnInit):

this.professionalDataForm = this.formBuilder.group({
  professionalRUT: this.formBuilder.control({value:'', disabled: false},[Validators.required]),
  professionalName: this.formBuilder.control({value:'', disabled: false}),
  address: this.formBuilder.control({value:'', disabled: false}),
  commune: this.formBuilder.control({value:'', disabled: false}),
  email: this.formBuilder.control({value:'', disabled: false})
});

And here the .html

<form [formGroup]="professionalDataForm">
<div class="row">
<mat-form-field class="col-md-4" appearance="outline">
  <mat-label>Rut del profesional</mat-label>
  <input matInput formControlName="professionalRUT" >
<mat-error class="line-broken-tooltip">
   adsf
  </mat-error> 
</mat-form-field>

thnks...

1 Answers

I don't think it's validating straight away, it's just that you need to control when mat-error should be shown or not. Looking at the example for the mat-form-field, your issue could be resolved with a simple ngIf.

<mat-form-field class="col-md-4" appearance="outline">
  <mat-label>Rut del profesional</mat-label>
  <input matInput formControlName="professionalRUT" >
  <mat-error class="line-broken-tooltip" *ngIf="professionalDataForm.controls?.professionalRUT?.invalid">
   adsf
  </mat-error> 
</mat-form-field>
Related