1

I am trying to understand how to use input file with Angular 2. In my example below, I would like my console to log the name of the file I have uploaded. Unfortunately, this code sends an error Cannot read property 'target' of undefined.

My component.html

<input 
   id="imageUpload" 
   type="file" 
   (change)="imageRun(input)"/>

My component.ts

imageRun(input){
    var files = input.target.files[0];
    console.log(files.name);
}

I am unsure if there is an Angular specific solution to this issue, as I have run into the same issue when doing this in plain javascript. I have looked over a few plain JS tutorials that all have me using the addEventListener method in JS, instead of assigning these triggers in HTML. But these methods, as far as I understand, do not really apply to an Angular 2 project.

For reference, here is an example of doing pretty much the same thing in plain JavaScript, and using addEventListener inside the src script.

1 Answer 1

1

You could define local template variable on inpit file element & use it inside a Component.

<Input #myInput
   id="imageUpload" 
   type="file" 
   (change)="imageRun(myInput)"/>

imageRun(input){
    var file = myInput.files[0];
    console.log(file.name);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Doing the first one leads to Cannot read property 'srcElement' of undefined. Will look into the second.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.