I'm trying to use onChange
function on a slider, but I keep getting and error with the Value. Am I doing something wrong ?
I'm using TypeScript and ViteJS.
My code:
<Slider
color="success"
aria-label="Small steps"
defaultValue={0.00000005}
step={1}
marks
min={5}
max={20}
valueLabelDisplay="auto"
value={passwordLength}
onChange={(e) => setPasswordLength(e.target.value)}
/>
I'm trying to use onChange
function on a slider, but I keep getting and error with the Value. Am I doing something wrong ?
I'm using TypeScript and ViteJS.
My code:
<Slider
color="success"
aria-label="Small steps"
defaultValue={0.00000005}
step={1}
marks
min={5}
max={20}
valueLabelDisplay="auto"
value={passwordLength}
onChange={(e) => setPasswordLength(e.target.value)}
/>
Share
Improve this question
edited Mar 14, 2022 at 3:46
bguiz
28.4k49 gold badges163 silver badges253 bronze badges
asked Mar 13, 2022 at 17:15
Cristian SuzukiCristian Suzuki
231 gold badge1 silver badge5 bronze badges
4 Answers
Reset to default 2in TypeScript and Angular
(input)="dt.filter(getTarget($event.target).value, // other code
and
getTarget(target: EventTarget | null): HTMLInputElement {
return target as HTMLInputElement;
}
Looking at the error reported: Property 'value' does not exist on type 'EventTarget'
Since you are using a custom ponent <Slider>
, you need to explicitly tell TypeScript the type of the HTMLElement
which is your target.
Look at this for more details
You should avoid e.target
, instead use e.currentTarget
.
In JavaScript e.target
refers to the element on which the event was fired, which may be the current element or it may be it's child. Usually for inputs you never have onChange events for children, but TypeScript doesn't know that, so it plains.
If you instead use e.currentTarget
then TypeScript will know that the target is not a child element of the Slider input, so it will allow you to use e.currentTarget.value
.
You can add $any to resolve the issue:
setPasswordLength($any(e.target).value)}