Search code examples
typescriptweb-componentcustom-elementlit-elementlit

How to get the tagname of a custom element from the outside (or even inside)?


My current approach:

Custom Element:

@customElement("bb-flow-identification")
export class FlowIdentification extends LitElement { /*...*/ }

Other location:

import { FlowIdentification } from "./flow-identification";

// The following yields the name of the class, e.g. 'FlowIdentification'
console.log(FlowIdentification.name);

How can I get the bb-flow-identification tagname from the 'Other location' file? And if that does not work, can I somehow access it from the 'Custom Element' file?

PS: This question is not specific to lit, but I'm having the problem too in the lit framework.


Solution

  • You can just rely on plain JavaScript semantics.

    export const ELEM_NAME = "bb-flow-identification";
    
    @customElement(ELEM_NAME)
    export class FlowIdentification extends LitElement {
    
      static registeredName = ELEM_NAME;
    }
    

    Then you can use it as:

    // Usage
    import { FlowIdentification, ELEM_NAME } from "./flow-identification";
    
    
    // Option 1
    console.log(ELEM_NAME);
    
    // Option 2
    console.log(FlowIdentification.registeredName);