-1

Is there any way to convert string as object property in angular? eg:

getErrorMessage(error_type) {
    return this.userForm.controls.{error_type}.hasError('required') ? 'You must enter a value' : '';
}

getErrorMesssage('email');

The function should work something like

return this.userForm.controls.email.hasError('required') ? 'You must enter a value' : '';
R. Richards
  • 23,283
  • 10
  • 63
  • 62
Bijesh Shrestha
  • 371
  • 2
  • 15

3 Answers3

3

You can use get() function:

getErrorMessage(controlName: string) {
    return this.userForm.get(controlName).hasError('required') ? 'You must enter a value' : '';
}

The only thing is that you want to pass the control name, not the error type, what I can see from your variable naming.

igor_c
  • 1,132
  • 1
  • 8
  • 19
1
getErrorMessage(error_type) {
  return this.userForm.controls[error_type].hasError('required') ? 'You must enter a value' : '';
}

Square brackets, not curly.

bryan60
  • 25,879
  • 3
  • 39
  • 55
0

In a general way, you can access object properties using bracket notation:

const thing = { email: 'foo@bar.com };
console.log(thing['email']); // prints 'foo@bar.com'
Will Alexander
  • 2,762
  • 1
  • 7
  • 16