首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在指令中获取组件选择器名称?角度4

如何在指令中获取组件选择器名称?角度4
EN

Stack Overflow用户
提问于 2018-01-15 16:41:52
回答 3查看 4.4K关注 0票数 2

我试图在指令中获得选择器的名字,我不确定这是不是可能的或者怎么做。

<my-component1 *myDir="Var"> </my-component1>
<my-component2 *myDir="Var"> </my-component2>
<my-component3 *myDir="Var"> </my-component3>

我在多个组件上使用相同的指令,就像上面给出的一样,现在我需要像下面这样在指令中获得当前组件的选择器名称。请告诉我如何在指令中获得选择器名称

@Directive({
  selector : '[myDir]

'
    })

    export class MyDirDirective {
       constructor (){
         this.currentSelector  = getCurrentComponentSelector;
       }
    }
     @Input() set myDir(value:any){
      if(this.currentSelector==='my-component1'){
          i will do some action, display or not decide
      }
    }
EN

回答 3

Stack Overflow用户

发布于 2019-05-16 07:07:17

这是一个更干净的解决方案,可以与AOT一起使用,并且当您在有问题的组件之外时:

const components = [ MyComponent ];
/*
  ...
  Anything that can be injected into
*/
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  // Loop through each component
  components.forEach(element => {
    // Get its resolved factory
    const factory = this.componentFactoryResolver.resolveComponentFactory(element);

    console.log('Factory:', factory);
    console.log('Selector:', factory.selector);
  });
}
票数 1
EN

Stack Overflow用户

发布于 2018-01-15 16:54:46

您应该使用ElementRef并获取标记名

constructor(private el: ElementRef) {
  const selector = el.nativeElement.tagName;
}

ngOnInit() {
  const selector = this.el.nativeElement.tagName;
}

(我不确定它是否能在构造函数中工作,所以测试这两个方法)

票数 0
EN

Stack Overflow用户

发布于 2018-01-16 20:38:14

我不确定这是否正确,但当我浏览templateRef整个响应时,我从下面的位置看到了组件选择器。因此,我将此作为临时解决方案。我希望这能帮助一些人。

this.templateRef'_def''template''element';

   export class MyDirDirective {
       constructor (private templateRef: TemplateRef<any>){
            this.currentSelector = this.templateRef['_def']['element']['template']['lastRenderRootNode']['element']['name'];
       }
    }

  @Input() set myDir(value:any){
      if(this.currentSelector === value){
          i will do some action, display or not decide
      }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48259416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档