angular - 从 Angular 2 组件中访问 `selector`

标签 angular angular2-directives angular2-components angular2-decorators

我想弄清楚如何访问我们传递给 @Component 装饰器的 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 查询来通过他们的选择器可靠地找到我的 Angular 元素。

我没有用 Protractor

最佳答案

使用ElementRef:

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

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

关于angular - 从 Angular 2 组件中访问 `selector`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37188216/

相关文章:

Angular2 http.request 无法添加 header

javascript - JS 工具到 Typescript

javascript - Angular 4如何在兄弟模块组件中使用另一个模块组件

html - 卡片组件内的 Bootstrap 4 按钮具有单击事件

angular - 如何将动态添加的自定义组件注册为表单组中的表单控件

Angular 2 RC 5 Bootstrap 自定义 HTTP 类 TypeError : Cannot read property 'toString' of null

angular - 如何使用指令设置 Angular 4 中 p-calendar 的区域设置属性?

angular - 如何使用 2 个参数创建主题(rx.js)?

Angular 2子组件检查父组件

css - 由于@Font-Face 在 Chrome 中呈现问题