nullnullnull
nullnullnull

Reputation: 8189

Get Ember component's name

If I call Ember.inspect(component), I get a response like:

<app@component:my-component::ember1246>

This suggests that the component is aware of its own name (my-component). Is there a way to access just that name?

Upvotes: 5

Views: 2344

Answers (2)

IAmJulianAcosta
IAmJulianAcosta

Reputation: 1212

This regex will do the trick:

//Returns a string with full name of component, like: <ProjectName@component:path/to/component-name::ember793>
let componentName = this.toString ();

//This regex will match the component and capture the latest part of component path.
let regex = componentName.match (/<[a-zA-Z]+@[a-zA-Z]+:(?:[a-z]+[\/])*([-a-z]+)::[a-zA-Z]+[0-9]+>/); 

//The latest element of array is the component name.
console.log (regex[regex.length-1]); //component-name

See https://regex101.com/r/rX9bQ7/3 for full explanation about how this works.

Upvotes: 0

Kit Sunde
Kit Sunde

Reputation: 37105

Ember.inspect() calls the objects toString() which in turn calls some internal ember metal functions to derive the name.

There is however an internal property which people have been using to get the name:

this.__proto__._debugContainerKey

This outputs component:my-component, then you can just split on :. There's an issue which will create a public way of exposing object meta information which we'll be able to use in the future: https://github.com/emberjs/ember.js/issues/10742

Upvotes: 7

Related Questions