简体   繁体   English

从 Angular 2 组件中访问“选择器”

[英]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.我试图弄清楚如何访问我们传递给@Component装饰器的selector器。

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.最终,我想用它来创建一个指令,自动添加一个属性data-tag-name="{this.component.selector}"以便我可以使用 Selenium 查询通过它们的选择器可靠地找到我的角度元素。

I am not using protractor我没有使用量角器

Use ElementRef :使用ElementRef

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

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

OUTDATED See https://stackoverflow.com/a/42579760/227299过时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重要说明运行AOT 编译器时注释会被删除,如果您正在预编译模板,则此解决方案无效

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

Here's an alternative if you need the selector name without access to the component's ElementRef :如果您需要选择器名称而无需访问组件的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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM