0

I have an attribute directive that I will be applying to elements in my DOM. I was wondering if it is possible to somehow get the component name that surrounds the attribute directive in the DOM.

For example, given:

<SomeComponent>
    <div myAttributeDirective>
</SomeComponent>

I want to get the name SomeComponent from within the attribute directive code.

I know I can pass in anything to the directive, but I'm trying to make it as succinct syntax as possible, and was hoping there was a creative way to accomplish this.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Parker
  • 123
  • 4
  • 16

3 Answers3

1

I did end up figuring out a way to do this, although it might be brittle in regards to future versions of Angular. The trick is to access the component instance from the ViewContainerRef within your directive, and then use the power of the component's constructor() to get the name.

import { Directive, HostListener, ViewContainerRef } from '@angular/core';
@Directive({
    selector: '[yourDirective]'
})
export class yourDirective {
    constructor(private _view: ViewContainerRef) {}
    ngOnInit {
        let component = (<any> this._view)._view.component;
        console.info("Component Name: ", component.constructor.name);
    }
}
Parker
  • 123
  • 4
  • 16
0

Nope, this is not possible from within the component tags. You have to pass in the components name by an attribute defined in the TS-file.

This article is about a similar topic, but even here you have to prepare a variable inside the TS-file that you then pass as an attribute.

Accessing `selector` from within an Angular 2 component

0

The typescript file core.d.ts file doesn't export the local _view object and you get an error in your linting or code completion when accessing _view. You can trick that like this:

const context = this.viewContainerRef['_view'].component.constructor.name;

But it can change after an update since this is not an exported part of the ViewContainerRef

Ron Jonk
  • 706
  • 6
  • 16