0
    private static addFieldError(form: FormGroup, fieldName: string, errorName: string) {
         form.controls[fieldName].setErrors({errorName: true});
         form.controls[fieldName].markAsTouched();
    }

Here setErrors is not as I would expect. This will set an error to the field with value: {errorName: true}

While debugging in Chrome

I would like to use the errorName: string parameter of the function addFieldError as the key of the object I am adding to error collection, and not using key 'errorName' itelf.

How can achieve that?

2
  • 2
    setErrors({[errorName]: true}) Commented Jan 9, 2020 at 22:22
  • Great! You can turn this into an answer with some explanation. It solves the problem. Commented Jan 11, 2020 at 22:28

1 Answer 1

3

All you need to do is output the variable value as a key name.

In your code the object key is errorName as string

setErrors({errorName: true})

But instead errorName is a variable to you and the value of this variable needs to be set as key name for the object computed.

setErrors({[errorName]: true})

This is an ES6 feature where you can get the key name computed from a variable.

Check Computed property names under Object initializer

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.