Find an element's containing component

Hi,

I was wondering if it’s possible to figure out the owning component in a custom attribute?
I know you can inject the Dom element in an attribute, I was wondering if there’s a way to figure out what aurelia component that element is a child of?

my-component-or-view.html

<template>
   <div my-custom-attribute="test"></div>
</template>

my-custom-attribute…ts

...
I want to get the 'my-component-or-view' name here
...

The specific use-case is that I want to write a custom translation attribute that automatically defines the i18N namespace based on the owning component. We want to split our translation namespaces on a per-component basis, but constantly repeating the namespace in each component isn’t very DRY. Any other suggestion in tackling this is much appreciated.

1 Like

You could look at the current binding context, e.g.:

// assuming you're in <my-component my-custom-attribute="">...</my-component>
class MyCustomAttribute{ 
  bind(bindingContext) {
      console.log(bindingContext.constructor.name); // prints: MyComponent 
  }
}

However this does not strictly give you the component that you’re working with, its often so accurate however when dealing with 3rd party plugins, custom bindings or dynamic composition, this may not work.

1 Like

Thanks, your answer got me looking at other lifecycle methods as well:
created(owningView: View, myView: View)

I can get the viewUrl from owningView.resources, which is probably a better candidate for extracting a namespace from?

1 Like

Hi ,

i dont know if this fits you usecase, but maybe this article could help? Sorry, for just posting a link.

Best

1 Like