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).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236
  • 1
    https://stackoverflow.com/questions/1894792/how-to-determine-whether-an-object-has-a-given-property-in-javascript could be helpful – Jota.Toledo Jun 27 '19 at 12:16
  • @Jota.Toledo hasOwnProperty does not seem to work for Angular component properties – Tom Smykowski Jun 27 '19 at 12:22
  • See [this post](https://stackoverflow.com/q/30207661/1009922). 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)`. – ConnorsFan Jun 27 '19 at 13:18
  • @ConnorsFan i get it. So how to do it? – Tom Smykowski Jul 03 '19 at 10:09
  • @TomaszSmykowski - [One answer](https://stackoverflow.com/a/43572554/1009922) suggests using custom transformers but I have never tried that. – ConnorsFan Jul 03 '19 at 15:51
  • @ConnorsFan It sounds like something to investigate further, thanks! – Tom Smykowski Jul 04 '19 at 16:48

1 Answers1

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

ihor.eth
  • 2,207
  • 20
  • 27