Property ‘value’ does not exist on type ‘EventTarget’ Error is a common error in Angular. It shows up when you try to access the value property of an HTML element during event binding.
Table of Contents
Property value does not exist on type EventTarget Example
The following are the examples, where you will see the above error
Example 1
1 2 3 4 | <input type="text" (input)="handleInput($event)" /> <p>You entered {{value1}}</p> |
1 2 3 4 5 6 7 8 | value1 = ""; value2 = ""; handleInput(event: Event) { this.value1 = event.target.value; } |
Example 2
1 2 3 4 | <input (keyup)="value2=$event.target.value)" /> <p>You entered {{value2}}</p> |
Reason for Error
This error is flagged by the TypeScript compiler.
The $event
in both examples are of type HTMLElement
. It can represent any HTML Element. Hence the value
property is not guaranteed to exist in the $event.target
.
Hence the TypeScript compiler throws an error.
The Error is also thrown in the component Template. This is because of the new angular projects sets the fullTemplateTypeCheck
to true
in tsconfig.json
.
Solution to the Problem
Component Class
The solution is to cast the event.target
to appropriate HTML element as shown below
1 2 3 4 5 | handleInput(event: Event) { this.value1 = (event.target as HTMLInputElement).value; } |
Component Template
To solve this problem, use the $any
typecast function ($any($event.target).value
) to stop the type checking in the template
1 2 3 4 | <input (keyup)="value2=$any($event.target).value" /> <p>You entered {{value2}}</p> |
Compiler Option
You can also set fullTemplateTypeCheck
to false
in tsconfig.json
. This will stop the Typescript compiler from running type check in Template.
You will find the fullTemplateTypeCheck
under the angularCompilerOptions
in the tsconfig.json
.
Thank you so much bro.
Thank you
thank you
Thank You
THANK YOU!!!!
appreciate man, thanks a lot.
My input type is
number
. I’m using the newly preferred method of using an #id and then use id.value but it types that asstring | number
and my property is a number. It would be nice if Angular also read the type of input. If$number($event.target).value
was an option that would be acceptable, but that doesn’t seem to be an option.I appreciate your good effors. Thanks a lot you really saved me.
Thank you so much for this solution “$any($event.target).value”!
It works for me
Thanks for your help! I almost didn’t find a solution anywhere.
Thankyou so much, component class solution works to me. full thanks bro
Thanks for this solution “$any($event.target).value”! All the answers on Stackoverflow were about a problem in the Class component not in the template.