3

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?

לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
RMD
  • 311
  • 1
  • 7
  • 22

2 Answers2

15

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>
Riverman
  • 503
  • 6
  • 17
1

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

Prathap Parameswar
  • 489
  • 1
  • 3
  • 11
  • Can you please describe this event emitter part as I am new to programming? – RMD Nov 04 '18 at 09:38
  • you can add event emitter in this tag to get the actual file user selected and send to modal if required detailed in https://stackoverflow.com/questions/38476315/angular2-file-input-onchange/38476440 – Prathap Parameswar Nov 04 '18 at 10:44
  • Though it opens the file explorer dialog box it does not show the attached item. – RMD Nov 05 '18 at 06:44
  • In the fileChange event you can capture the filename and assign to variable and show it in another div using angular template expression https://angular.io/guide/template-syntax – Prathap Parameswar Nov 05 '18 at 08:23