abrahamlinkedin abrahamlinkedin - 1 year ago 364
Javascript Question

Angular 2 read input file

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


My component.ts

var files = input.target.files[0];

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
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.

Answer Source

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

<Input #myInput

    var file = myInput.files[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download