-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
  • 24,603
  • 10
  • 64
  • 64
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,200
  • 1
  • 8
  • 20
1
getErrorMessage(error_type) {
  return this.userForm.controls[error_type].hasError('required') ? 'You must enter a value' : '';
}

Square brackets, not curly.

bryan60
  • 28,215
  • 4
  • 48
  • 65
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
  • 3,425
  • 1
  • 10
  • 17