Accessing `selector` from within an Angular 2 component

后端 未结 2 919
感动是毒
感动是毒 2020-12-09 17:17

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

For example

@Componen         


        
相关标签:
2条回答
  • 2020-12-09 17:57

    Use ElementRef:

    import { Component, ElementRef } from '@angular/core'
    
    @Component({
      selector: 'my-component'
    })
    export class MyComponent {
      constructor(elem: ElementRef) {
        const tagName = elem.nativeElement.tagName.toLowerCase();
      }
    }
    
    0 讨论(0)
  • 2020-12-09 18:11

    OUTDATED See https://stackoverflow.com/a/42579760/227299

    You need to get the metadata associated with your component:

    Important Note Annotations get stripped out when you run the AOT compiler rendering this solution invalid if you are pre compiling templates

    @Component({
      selector: 'my-component'
    })
    class MyComponent {
      constructor() {
        // Access `MyComponent` without relying on its name
        var annotations = Reflect.getMetadata('annotations', this.constructor);
        var componentMetadata = annotations.find(annotation => {
          return (annotation instanceof ComponentMetadata);
        });
        var selector = componentMetadata.selector // my-component
      }
    }
    
    0 讨论(0)
提交回复
热议问题