8

我在想如何访问我们传入@Component装饰器的selector从Angular 2组件中访问`selector`

例如

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

最后,我想用它来创建一个指令,它会自动添加一个属性data-tag-name="{this.component.selector}",这样我可以用Selenium查询可靠地找到我通过自己选择的角度元素。

我不是用量角器

回答

12

使用ElementRef

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

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

这可能是现在唯一的方法,现在更老的(现在打破)的方式更好,因为它不需要添加注入,并且可以在不需要实例的情况下访问它,在写入结束时使用它结束测试以减少重复。 –

7

过时https://stackoverflow.com/a/42579760/227299

你需要得到您的组件相关的元数据:

重要提示注解,当您运行AOT compiler得到剥离出来如果您正在编译模板,则使此解决方案无效

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

这看起来很有希望,'如何Reflect.getMetadata'能够知道它应该寻找的'MyComponent'元,如果我们不告诉它什么?当我调用Reflect.getMetadata('annotations')时,我目前收到错误;错误是Reflect.getMetadata('annotations') VM61 angular2.sfx.dev.js:2652 Uncaught TypeError(...)getMetadata @ Reflect.getMetadata('annotations',this,'annotations')'看起来它需要两个额外的参数 –

+1

通过传递'this.constructor'作为第二个参数来解决您的问题。 –

+2

请使用适用的Angular 2版本来限定此答案 - 从版本2.3.0开始,这似乎已过时 – Neoheurist