Reputation: 2471
I am building an application in Angular 8 with Material and Reactive Forms. I have a reactive form with the fields ItemID, Title and Description.
There is a search button next to the ItemID field that sends an HTTP request to get data from an external API. This is all working properly. However, after the search button is clicked and the response is returned, the validation is highlighting the Title and Description fields in red, even though the fields have not been touched yet and are pristine. Since the fields have not been touched yet, they should not be highlighted in red.
Here are the classes that are applied to the form control when it is highlighted in red even though it is still untouched and pristine.
mat-form-field ng-tns-c9-58 mat-primary mat-form-field-type-mat-input mat-form-field-appearance-outline mat-form-field-can-float mat-form-field-should-float mat-form-field-has-label ng-untouched ng-pristine ng-invalid mat-form-field-invalid
TS Component
constructor(
private fb: FormBuilder
) { }
// Initialize Item Detail form
this.itemDetailForm = this.fb.group({
Item: this.fb.group({
ItemID: [null],
}),
Title: [null, Validators.compose([
Validators.required,
Validators.maxLength(10),
])],
Description: [null, Validators.compose([
Validators.required,
Validators.maxLength(10),
});
HTML Component
<form [formGroup]="itemDetailForm" (ngSubmit)="onSubmit()">
<div formGroupName="Item">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Item ID</mat-label>
<input matInput formControlName="ItemID">
</mat-form-field>
<button mat-raised-button (click)="onItemSearch(this.itemDetailForm.get('ItemID').value)"
[disabled]="itemDetailForm.get('ItemID').invalid">
<mat-icon>search</mat-icon>
</button>
</div>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Title</mat-label>
<input matInput formControlName="Title">
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Description</mat-label>
<input matInput formControlName="Description">
</mat-form-field>
</form>
Upvotes: 9
Views: 5726
Reputation: 1599
This is because any button inside a form element will by default run a native submit function which validates your inputs.
Use type="button"
on the button element. By default type="submit"
Upvotes: 20