4

In an Angular2 Component, when doing:

console.log (this);

you get as expected the whole object with all members, e.g.

"ComponentName {member1, member2, member_n}"

Now I want to only log the ComponentName. How to achieve?

4
  • what is ComponentName? have you tried this.ComponentName ? Commented Sep 19, 2016 at 15:39
  • Here, ComponentName is the name of the component, e.g. in Angular 2 we do: export class MySuperCoolComponent { .. } Commented Sep 19, 2016 at 15:49
  • nice question but strange one... Commented Sep 19, 2016 at 15:50
  • In complex software projects, when you want to do modular logging (maybe even into some REST service), you won't find the question strange anymore. Commented Sep 19, 2016 at 15:53

1 Answer 1

10

Really interesting question, this is what you are looking for:

console.log(this.constructor.name);
Sign up to request clarification or add additional context in comments.

3 Comments

Great reply, thanks! Confirmed Working on all my Services and Components.
@Stefan very nice answer,
This works. However, be aware that angular-cli/webpack and other name-shortening JavaScript minify tools may change your class name to a single letter. So in dev mode it'll be "MyClass" but after minification just a single letter "a". This can be annoying if you need to look at production console logs or break your code if you use this.constructor.name for logic.

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.