How to use input type file in angular material

Hariom Singh picture Hariom Singh · Oct 3, 2018 · Viewed 56k times · Source

How to use input type file in angular material

Hi, I am using angular material for designing. when i go on angular material site there no input type file element. anyone know about this.

Answer

JackMorrissey picture JackMorrissey · Nov 29, 2018

Here is a workaround if all you want is a nicely displayed file input button.

Html

<button type="button" mat-raised-button (click)="fileInput.click()">Choose File</button>
<input hidden (change)="onFileSelected()" #fileInput type="file" id="file">

Component

onFileSelected() {
  const inputNode: any = document.querySelector('#file');

  if (typeof (FileReader) !== 'undefined') {
    const reader = new FileReader();

    reader.onload = (e: any) => {
      this.srcResult = e.target.result;
    };

    reader.readAsArrayBuffer(inputNode.files[0]);
  }
}

Inspired by this Angular Material Github Issue comment https://github.com/angular/material2/issues/3262#issuecomment-309000588