How to open file dialog box when click an image in Angular 6

Viewed 14115

I am new to Angular 6. I know this may be silly but I did not get any solution. I want to open file dialog box when click the browse image which is in the text field. This is what I have tried.

<div class="boxed">
  <div class="input-group">
      <input id="spFile" class="form-control" name="spFile">
    <img src="../../../../../assets/images/maps/Browse.png" type= "file" width="40" height="40" style=" position: absolute; top: 1px; right: 1px" aria-hidden="true"/>
  </div>
</div>

How can I make this to open a file dialog box easily?

2 Answers

This is a relatively old question, but I have a simple yet smooth solution for this question for people coming here just now.

Add an ID to your <input> HTML element (It's FileSelectInputDialog in my example).

<input #FileSelectInputDialog type="file" multiple/>

Create a handle to it in your component using ViewChild:

import { ViewChild } from '@angular/core';

@ViewChild('FileSelectInputDialog') FileSelectInputDialog: ElementRef;

public OpenAddFilesDialog() {
    const e: HTMLElement = this.FileSelectInputDialog.nativeElement;
    e.click();
}

Then you can add the (click)="OpenAddFilesDialog()" directive to your image or to any other HTML element, for example, to a regular button:

<button mat-icon-button class="BtnAddFiles" (click)="OpenAddFilesDialog()">
    <mat-icon>add_box</mat-icon>
</button>

create input with file type and add css to show it as an image

<div class="boxed">
  <div class="input-group">
      <input id="spFile" class="form-control" name="spFile">
    <input type="file" class="filepicker">
  </div>
</div>

css follows

.filepicker{
    -webkit-appearance: none;
    position:absolute;
    top:1px;
    right:1px;
    width: 40px;
    height: 40px;
    text-indent: 100em;
    background: url('assets/images/maps/Browse.png');
    background-size: cover;
    overflow: hidden;
    cursor: pointer;
    outline: none;
}

also add an event emitter to capture change event like (change)="onChange($event)".

Related