0

I have project written in Angular and I want to style input type file. So in the Internet I have found solution that I have to hide input type file and call its event programmatically. But below code doesn't to work:

   <input type="button" id="addImgFile" value="Add file" 
onclick="var addImgFile = document.getElementById('addImgFile'); var event = new Event('change'); addImgFile.dispatchEvent(event);" />
    <input type="file" name="avatar" id="addImgFile" style="display:none;" 
(change)="onFileChange($event)" />
0

4 Answers 4

1

Instead of using another input you could use label to get your desire style. Here is an example

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

Comments

0

In Angular, you should use the ViewChild property dectorator to access to the element. You can then manually execute any method you need from your typescript file. Here is a basic example: https://stackblitz.com/edit/angular-nfdvsr

Comments

0
<input type="button" id="addImgFile" value="Add file" (click)="onAddFile()" />
<input #file type="file" name="avatar" id="addImgFile" style="display:none;" 
(change)="onFileChange($event)" />
@ViewChild('file', { static: true })
private file: ElementRef;

onAddFile() {
   // manually click the file element
   this.file.nativeElement.value = null;
   this.file.nativeElement.click();
}

1 Comment

@Robert, nice !!
0

Not quite clear what you want to achieve, but if you just want to hide the input field in beginning and show it only on click of "add file" button then you can try changing button's event as per below code.

<input type="button" id="addImgFile" value="Add file" onclick="var addImgFile = document.getElementById('addImgFile1'); var event = new Event('change'); addImgFile.dispatchEvent(event);" />

<input type="file" name="avatar"  id="addImgFile1" style="display:none;" onchange=" event.target.style=''; event.target.click()" />

3 Comments

I wanted to fire input type file click, not only to hide it, but thanks for response :)
Edited answer, which could serve the your purpose.
Please check now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.