Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing `selector` from within an Angular 2 component

I'm trying to figure out how I can access the selector that we pass into the @Component decorator.

For example

@Component({
  selector: 'my-component'
})
class MyComponent {
  constructor() {
     // I was hoping for something like the following but it doesn't exist
     this.component.selector // my-component
  }
}

Ultimately, I would like to use this to create a directive that automatically adds an attribute data-tag-name="{this.component.selector}" so that I can use Selenium queries to reliably find my angular elements by their selector.

I am not using protractor

like image 644
Juan Mendes Avatar asked May 12 '16 13:05

Juan Mendes


3 Answers

Use ElementRef:

import { Component, ElementRef } from '@angular/core'

@Component({
  selector: 'my-component'
})
export class MyComponent {
  constructor(elem: ElementRef) {
    const tagName = elem.nativeElement.tagName.toLowerCase();
  }
}
like image 65
Anton Poznyakovskiy Avatar answered Nov 13 '22 11:11

Anton Poznyakovskiy


OUTDATED See https://stackoverflow.com/a/42579760/227299

You need to get the metadata associated with your component:

Important Note Annotations get stripped out when you run the AOT compiler rendering this solution invalid if you are pre compiling templates

@Component({
  selector: 'my-component'
})
class MyComponent {
  constructor() {
    // Access `MyComponent` without relying on its name
    var annotations = Reflect.getMetadata('annotations', this.constructor);
    var componentMetadata = annotations.find(annotation => {
      return (annotation instanceof ComponentMetadata);
    });
    var selector = componentMetadata.selector // my-component
  }
}
like image 27
Thierry Templier Avatar answered Nov 13 '22 12:11

Thierry Templier


Here's an alternative if you need the selector name without access to the component's ElementRef:

const components = [MyComponent];

for (const component of components) {
  const selector = component.ɵcmp.selectors[0][0];
  console.log(selector);
}

Honestly, this first method feels rather hacky and who knows if this ɵ is supposed to just be for internal use? I thought I'd include it so that maybe someone could shed some light on it?

So, this is probably a safer route:

constructor(private factory: ComponentFactoryResolver) {
  const components = [MyComponent];

  for (const component of components) {
    const { selector } = this.factory.resolveComponentFactory(component);
    console.log(selector);
  }
}
like image 7
Drew Payment Avatar answered Nov 13 '22 11:11

Drew Payment