Home > Mobile >  How to bind error for form fields in Angular 8 app?
How to bind error for form fields in Angular 8 app?

Time:09-08

I have a subscribe block where I am able to catch a custom error object which sent back from spring boot.

.subscribe((data) => {            
},
(err) => {
  //console.log(err);
  let httpErrorResponse: HttpErrorResponse = err;
  let errorResponse: ErrorResponse = httpErrorResponse.error;
  console.log(errorResponse);
  if (errorResponse != null && errorResponse != undefined 
      && errorResponse.errors != null) {
     errorResponse.errors.forEach(error => {
        console.log(error.field_bame   " "   error.message);
        let fieldName = error.field_bame;
        let message = error.message;
        listingFormDirective.form.controls['${fieldName}'].setErrors({'existCompany': true});         
    }) 
  }
  
});

What I'm trying to do here is to have genreic method (util class) to bind each field for error for all the Angular applciation. the problem is here:

form.controls['${fieldName}']

I tried also:

   form.controls[fieldName]

The error from the consule:

core.js:7187 ERROR TypeError: Cannot read properties of undefined (reading 'setErrors')

CodePudding user response:

use back-ticks instead of single quotes

for ex:

form.controls[`${fieldName}`]
  • Related