Angular2 - 是否可以使用选择器名称获取组件类名称 [英] Angular2 - is it possible to get component class name using selector name

查看:25
本文介绍了Angular2 - 是否可以使用选择器名称获取组件类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Angular 2 中使用选择器名称获取组件类名称或组件引用?

Is it possible to get component class name or component reference using selector name in Angular 2?

@Component({
  selector: 'selector-1',
  template: '<h1>Hello</h1>',
})
export class Component1 {}

@Component({
      selector: 'selector-2',
      template: '<h1>Hello</h1>',
    })
    export class Component2 {}

在组件 2 中是否可以使用选择器selector-1"获取组件 1 的类名?

In component 2 is it possible to get the component1 class name using selector "selector-1"?

示例:

getComponentName(selectorName) {
 // return component name
}

getComponentName('selector-1');

提前致谢

推荐答案

只有不调用 enableProdMode 才可能无需额外工作:

It is possible without additional work only if you do not call enableProdMode:

var node = document.querySelector('selector-1');
var debugNode = window.ng.probe(node);
var name = debugNode.componentInstance.constructor.name;

否则你将不得不自己维护组件映射.

Otherwise you will have to maintain component map yourself.

这篇关于Angular2 - 是否可以使用选择器名称获取组件类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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