首页 > 解决方案 > 如何在属性指令的逻辑中获取组件名称?

问题描述

我有一个属性指令,我将应用于我的 DOM 中的元素。我想知道是否有可能以某种方式获取 DOM 中属性指令周围的组件名称。

例如,给定:

<SomeComponent>
    <div myAttributeDirective>
</SomeComponent>

我想SomeComponent从属性指令代码中获取名称。

我知道我可以将任何内容传递给指令,但我正在尝试使其语法尽可能简洁,并希望有一种创造性的方式来实现这一点。

标签: angularangular-directive

解决方案


我最终确实找到了一种方法来做到这一点,尽管它对于 Angular 的未来版本可能很脆弱。诀窍是从指令中访问组件实例ViewContainerRef,然后使用组件的强大功能constructor()来获取名称。

import { Directive, HostListener, ViewContainerRef } from '@angular/core';
@Directive({
    selector: '[yourDirective]'
})
export class yourDirective {
    constructor(private _view: ViewContainerRef) {}
    ngOnInit {
        let component = (<any> this._view)._view.component;
        console.info("Component Name: ", component.constructor.name);
    }
}

推荐阅读