I have an Angular application which has a HttpInterceptor configured to catch server side validation errors.
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
if (error.status === 400) {
if (error.error.constructor == Object) {
let validationErrorDictionary = error.error;
var errors = [];
for (var fieldName in validationErrorDictionary) {
if (validationErrorDictionary.hasOwnProperty(fieldName))
{
let description = validationErrorDictionary[fieldName];
errors.push(description);
}
}
this.alertService.validationError(errors)
} else {
this.alertService.validationError([error.error])
}
return throwError(error);
}
})
)
}
This works well, and in my form I see my alertComponent show a list of errors that have been sent to my Alert Service.
How do I highlight the appropriate field in my reactive form?
Ie. if I have a form like this:
this.productForm = this.fb.group({
name: [this.model.name, Validators.required],
price: [this.model.price],
})
And price comes back with a server side error that is picked up by my interceptor, how do I display an error on that field? (In this case I'm using Angular Material)
<mat-form-field hideRequiredMarker appearance="standard">
<mat-label>Price</mat-label>
<input matInput maxlength="10" formControlName="price">
<mat-error>There was an error with the price</mat-error>
</mat-form-field>