1

I have a property of a component in Angular that looks like this:

export class CarComponent implements OnInit {
  partNumber: number;

  checkIfItHasAPartNumberProperty() {
      return this.hasAProperty('partNumber');
  }

What is Angular equivalent for hasAProperty to check if this class contains a definition of a property by string name, eg. "partNumber"?

It is not a question about getting value of "partNumber", or checking directly if it has property "partNumber", but check programmatically if a component has a property of a given name (by string).

6
  • 1
    stackoverflow.com/questions/1894792/… could be helpful Commented Jun 27, 2019 at 12:16
  • @Jota.Toledo hasOwnProperty does not seem to work for Angular component properties Commented Jun 27, 2019 at 12:22
  • See this post. The properties that have been initialized can be retrieved with hasOwnProperty but the others are not present in the class instance at runtime. You can see that with console.log(this). Commented Jun 27, 2019 at 13:18
  • @ConnorsFan i get it. So how to do it? Commented Jul 3, 2019 at 10:09
  • @TomaszSmykowski - One answer suggests using custom transformers but I have never tried that. Commented Jul 3, 2019 at 15:51

1 Answer 1

2
 const obj = this as object;
 obj.hasOwnProperty('prop')

Cast this to object and you should be able to call hasOwnProperty on it

EDIT This wont work on properties that haven't been initialized. For that case (if possible in your scenario) initialize the property with null and the above code will work

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.