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?

1

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Can you please describe this event emitter part as I am new to programming?
you can add event emitter in this tag to get the actual file user selected and send to modal if required <input type="file" class="filepicker" (change)="onChange($event)"> detailed in stackoverflow.com/questions/38476315/…
Though it opens the file explorer dialog box it does not show the attached item.
In the fileChange event you can capture the filename and assign to variable and show it in another div using angular template expression angular.io/guide/template-syntax

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.