3

I want to list all the component properties (both private and public) in angular.

I have tried the following

ngOnInit() {
    console.log(this.constructor.prototype);
}

But this is printing only the properties that have getter methods defined. It is not printing the properties which do not have getters or setters. It also prints component methods which I am not bothered.

Strange part is, it is not even displaying the public properties (which do not have getters).

Even I tried doing

console.log(this.constructor.prototype.hasOwnProperty('_queryState'));

But it returns me false, which means it was not able to identify the property.

This question does not help me though.

How do I list all the properties?

If anyone is asking me why do I need to do this, it is for unit testing.

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98

1 Answers1

0

You could use javascript Object.keys :

let component = {a: 17, b: 'test', c: [17, 17, 17]};
let keys = Object.keys(component);

for(let key of keys) {
  console.log('component[' + key + '] = ' + component[key]);
}

Here is a running stackblitz example.

ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
  • 1
    component is not a javascript object in my case. It is an angular component. And also `Object.keys(this.construtor.prototype)` does not print private properties even though they are initialized. – Amit Chigadani Jun 05 '18 at 13:51
  • How do you declare your component ? The stackblitz example logs an angular component properties into console. – ibenjelloun Jun 05 '18 at 13:59
  • Sorry, I had got confused. The private properties don't show up if I don't initialize them first. I guess I really don't have a nice way to do it. https://stackoverflow.com/questions/49174696/get-class-interface-properties-in-angular-5-typescript-without-assigning-a-d/49174833#49174833. – Amit Chigadani Jun 05 '18 at 14:46