Can I assign a variable as value to an object's key?

41 views Asked by At

Is this allowed?

export class H{
passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
...

validatePassword(control: FormControl) {
...
    return (REG_EXP.test(password)) ? null : {
      validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
        valid: false,
        message:  this.passwordErrorMessage //can I do this?
      } 
    };
  }
}

For one of my test cases, I am getting the following error

TypeError: Cannot read property 'passwordErrorMessage' of undefined
Error object: Property name: ngDebugContext, value: [object Object]
Error object: Property name: ngErrorLogger, value: function () { [native code] }
TypeError: Cannot read property 'passwordErrorMessage' of undefined
    at HelperService.validatePassword (webpack:///./src/app/helper.service.ts?:224:31)

It seems this is undefined. I am still in early stages of debugging but my first doubt is if the usage of this is correct? Things work fine if I change the usage to message: 'Password must contain 1 small-case alphabet, 1 capital alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'

1

There are 1 answers

4
Ethan Lipkind On BEST ANSWER

yes you can, but you'll need to either bind validatePassword to the class or use an arrow function to pass this context into the function. this should work:

export class H{
    passwordErrorMessage = 'Password must contain 1 small-case alphabet, 1 capital  alphabet, 1 digit, 1 special character. The length should be 6-10 characters.'
    ...

    validatePassword = (control: FormControl) => {
        ...
        return (REG_EXP.test(password)) ? null : {
          validatePassword: { // check the class ShowErrorsComponent to see how validatePassword is used.
            valid: false,
            message:  this.passwordErrorMessage
          } 
    };
  }
}