Home > Blockchain >  Angular - mat-field gets validated without touching it
Angular - mat-field gets validated without touching it

Time:10-13

I have the following field:

    <mat-form-field appearance="outline">
        <mat-label>ABC</mat-label>
        <input matInput formControlName="xyz">            
        <mat-error 
            // form.controls['xyz'].dirty &&  
            form.controls['xyz'].errors?.required">
            <span>Show error</span>
    </mat-form-field>

I also have a button:

    <button type="file" mat-stroked-button><span>Cancel</span>
    </button>

When I click on the button the error validation is triggered and an error is shown. If I uncomment "dirty" line then that is not happening. Why would form validation is triggered if I haven't touched the field yet?

Thanks for help.

CodePudding user response:

I am not an expert, but are your elements in a <form> tag?

One of the reasons, I would expect this to happen, is that you haven't defined the "type" property for your button.

What happens if you define type="button"? Does it behave differently?

link: https://www.w3schools.com/tags/att_button_type.asp

I hope this helps :)

CodePudding user response:

This is a known 'issue' in Angular.

You can mark the form as Pristine and disable the input until is touched.

// In component.ts file
form.markAsPristine();

<mat-form-field appearance="outline">
  <mat-label>ABC</mat-label>
  <input matInput [disabled]="form.pristine" formControlName="xyz">  // add disabled          
   <mat-error 
    // form.controls['xyz'].dirty &&  
    form.controls['xyz'].errors?.required">
   <span>Show error</span>
</mat-form-field>

For more info https://angular.io/api/forms/AbstractControl

  • Related