Reputation: 467
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.
Upvotes: 1
Views: 1317
Reputation: 136144
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);
}
Upvotes: 1