1

I want to add a image to file type variable in angular2

I tried it like this

private file:File;

setImage(){
  this.file = "../assets/image/image.jpg"
} 

but it's not working.

1 Answer 1

3
private file:File;
this.file = "../assets/image/image.jpg"

I'm pretty sure the typescript compiler is telling you that you can't assign a String to a File type. That is why it's not working. In other words when you say that file is of type File then the typescript compiler is expecting a special kind of object, a File object. If you assign a string to it it will tell you it's wrong. When you write :File it isn't just a decoration, it tells typescript, hey I intend this to be a File, so if I assign anything else, make sure to scream at me.

So you could just do this, if you want a string:

private file:string;
this.file = "../assets/image/image.jpg"

Or if you want a legal File object the doc on File here https://developer.mozilla.org/en/docs/Web/API/File says this:

new File(
  Array parts,
  String filename, 
  BlobPropertyBag properties
);

So :

  file:File = new File(this.data , "filename");

Or if you want to be free of charges:

file:any;

On a side note, you should read the doc or the quickstart because if you don't understand typing, then there is no point in using typescript notations in the first place.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.