从Angular 2组件中访问`selector` [英] Accessing `selector` from within an Angular 2 component

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

问题描述

我试图弄清楚如何访问传递给@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组件中访问`selector`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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