Marko Lojanica
Marko Lojanica

Reputation: 3

Custom web components vanilla JavaScript

Is there any way to pass parameters to the custom web component ? I need parameters for my component . Class is extended html collection.

class CustomDropdown extends HTMLElement{

    constructor(){

        super();

        this.shadow = this.attachShadow({ mode : 'open' });

        this.setAttribute('expanded', there should be some parameter );

    }
}

Upvotes: 0

Views: 380

Answers (1)

mgarcia
mgarcia

Reputation: 6325

Normally, when you use your custom component you pass the parameters as attributes:

<custom-dropw-down expanded="true"></custom-drop-down>

Then, in the connectedCallback hook you can retrieve them:

connectedCallback() {
    const isExpanded = this.getAttribute('expanded');
}

If you want to set an attribute to the rendered DOM, you should also do that once the component has been rendered (for example, in the connectedCallback hook):

connectedCallback() {
    this.setAttribute('expanded', 'true');
}

Upvotes: 1

Related Questions