0

I want to set the value of an ion-input field when the page is loaded. I'm trying to get the element from the shadowDom using the shadowRoot querySelector. It is a stencil project with ionic. The component uses the shadowDOM. When I try to get the value my IDE says:

IDE error message

The nameEl:

const nameEl = this.el.shadowRoot.querySelector('#name');

The value will be set correctly, but I was wondering how I could fix this error message.

EDIT: Answer as suggested by Ash is correct. And like Ash mentioned there are two ways of implementing this solution. But I was wondering if there is any difference between the solutions?

const nameEl = this.el.shadowRoot.querySelector('#name') as HTMLInputElement;

or

const nameEl: HTMLInputElement = this.el.shadowRoot.querySelector('#name');

EDIT: The solution of course also work as one-liners as in Ash his example. (this.el.shadowRoot.querySelector('#name') as HTMLInputElement).value

And in my case the input is a ionic input: (this.el.shadowRoot.querySelector('#name') as HTMLIonInputElement).value

Mike Manders
  • 115
  • 2
  • 13

1 Answers1

2

Setting the value works as you said but the reason for the error is as the message says Property 'value' does not exist on type 'Element'. To phrase it differently to help you understand, the message is saying:

  • You have something of type Element
  • The value property does not exist on the type definition for that something

Therefore you need to either correct the code to get the right type of element or in your case tell the code what to expect.

(<HTMLInputElement>nameEl).value
// OR
(nameEl as HTMLElement).value

The above snippets were taken from the related questions below and updated to match your variable names.

I answered here because you mentioned Stencil but is not related to the issues, however this question is a duplicate and answers for similar questions can be found at Property 'value' does not exist on type 'EventTarget' and Property 'value' does not exist on type EventTarget in TypeScript

Ash
  • 11,292
  • 4
  • 27
  • 34