1

I created stand alone web component, with Vite and Vue3, to replace old jQuery libraries.

When rendered in html, it looks something like:

<custom-datepicker id="deliveryTime">
  #shadow-root
  <div>...actual component...</div>
</custom-datepicker>

When user select date it would be perfect if I can set attribute value to this element, like:

<custom-datepicker value="selected value HERE" ...

so the form can then use this value from the element by it's id.

Problem is that the only way I manage to achieve this is by emitting event (selected) from my web component and listening to that event, so the form can use value, like:

const datepicker = document.querySelector('#deliveryTime');
const dateSelected = (e) => {
  datepicker.value = e.detail.val;
}
window.addEventListener('selected', dateSelected);

If I set value attribute within web component, rest of the app (Apache Velocity template) can't access it because it is in the shadow-root:

<custom-datepicker id="deliveryTime">
  #shadow-root
  <div value="selected value is sadly HERE">...actual component...</div>
</custom-datepicker>

Is it even possible to achieve this from inside the web component (so I can omit listener)?

2 Answers 2

2

I found solution, maybe not the cleanest one but it works :)

In my web-component, in mounted hook component is selected:

const dp = ref(null)
onMounted(() => {
  dp.value = document.querySelector("#deliveryTime");
})

After date is selected, instead of emitting just set attribute:

dp.value.setAttribute('value', value)
Sign up to request clarification or add additional context in comments.

Comments

0

What if you access the HTMLElement linked to your shadowhost and then use the "setAttribute" function on it ? Assuming you have access to the shadowRoot inside your component using 'this', I think something like that will do the trick (https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/host) :

const shadowHost = this.shadowRoot.host; // The HTMLElement linked to <custom-datepicker />
shadowHost.setAttribute("value", someValueOfYourChoice);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.