从 Angular 2 组件中访问“选择器" [英] Accessing `selector` from within an Angular 2 component

查看:28
本文介绍了从 Angular 2 组件中访问“选择器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何访问我们传递给 @Component 装饰器的 selector.

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

例如

@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查询以通过它们的选择器可靠地找到我的角度元素.

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.

我没有使用量角器

推荐答案

使用 ElementRef:

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

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

这篇关于从 Angular 2 组件中访问“选择器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆