Accessing `selector` from within an Angular 2 component

可紊 提交于 2019-11-29 13:17:39

问题


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


回答1:


Use ElementRef:

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

@Component({
  selector: 'my-component'
})
export class MyComponent {
  constructor(elem: ElementRef) {
    const tagName = elem.nativeElement.tagName.toLowerCase();
  }
}



回答2:


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
  }
}


来源:https://stackoverflow.com/questions/37188216/accessing-selector-from-within-an-angular-2-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!