Search code examples
javascripttypescriptweb-componentstenciljs

How can I access native HTML attributes in stenciljs? And how to make it appear in the documentation?


The web components made with stenciljs don't extend HTMLElement. How can I access the native attributes and use them in my component, say the title attribute? When I add @Prop() title and use it in my template an error is shown.

Adding @Prop() also makes the attributes visible in the generated documentation. How can I add the used or required native attributes to the generated documentation?

Compiler error I'm getting:

The @Prop() name "title" is a reserved public name. Please rename the "title" prop so it does not conflict
with an existing standardized prototype member. Reusing prop names that are already defined on the element's
prototype may cause unexpected runtime errors or user-interface issues on various browsers, so it's best to
avoid them entirely.

Solution

  • Yes, you are not allowed to do so but you can pass HTML attributes directly to the element without declaring them with the @Prop decorator. In your case, just pass title to your component.

    <your-component title="test title"></your-component>
    

    Then, if you would like to read the value of your title attribute, you have to get the reference to the host element first.

    @Element() host: HTMLElement;
    

    Then, you can read it with your host element's getAttribute method, for instance:

    componentDidLoad() {
      const title = this.host.getAttribute('title');
      console.log(title); // or do something with it
    }