When we are working on Angular, many times we may want to pass some data from the template to the component ‘ts’ file. If you try to pass a ‘file’ using input element , then you may come across the error “Property files does not exist on EventTarget” in strict mode.

The code that is causing the above error is

Copy to Clipboard

Reason for the Error:

In HTML, we will be having many times of elements. Text related elements (h1, p etc.,), Input Elements, Buttons etc., It is not possible for TypeScript¬† to detect the type of the element whose data we are trying to access. By default it considers the $event as a general Event. If the Event’s target is not an Input element, it will not have the ‘files’ property. Only the events which are triggered by Input elements will have the ‘files’ property on its ‘target’. Since TypeScript cannot generalize, it throws the error in strict mode.

Solution for “Property files does not exist on EventTarget in Angular”

There are different ways to solve this problem in Angular.

Solution 1

Instead of passing only ‘files’ data from the template, we can pass the entire ‘$event’ and fetch the files property in the ‘ts’ file.

We can modify our HTML to this

Copy to Clipboard

then, we can change our ‘ts’ file accordingly like this

Copy to Clipboard

With the above code, we are explicitly telling TypeScript that the element that is triggering the event is an HTMLInputElement.

Solution 2 for Property ‘x’ does not exist on EventTarget

If you do not have control over the ‘ts’ file and if you must have to do it only in the template, then you have to do ‘type cast in template’ .

How to Cast in Template in Angular ?

Though casting from one type to another is straight forward thing in ‘ts’ it is not in HTML. From Angular 8, it offers a new ‘cast function @any()’ to silence the error.

You can change your template code to the following

Copy to Clipboard

this method is similar to using the TypeScript data type ‘any’ (a not recommended data type) but inside the template.

This type of error can arise not only for the ‘files’, but also for any other type of property such as ‘value’.

If you have any other solution, please let us know through the comments below.