Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use input type file in angular material

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.

like image 969
Hariom Singh Avatar asked Oct 03 '18 07:10

Hariom Singh


3 Answers

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

like image 50
JackMorrissey Avatar answered Oct 22 '22 22:10

JackMorrissey


Angular Material does not support yet a workaround for file upload. There are alternative to archieve this. e.g using external libraries.

angular-material-fileupload: link to npm package

Supported features:

  • Drag and drop
  • common uploads
  • progress bar
  • file size and more...

ngx-material-file-input: Link to repository

Supported features:

  • ngx-mat-file-input component, to use inside Angular Material mat-form-field
  • a FileValidator with maxContentSize, to limit the file size
  • a ByteFormatPipe to format the file size in a human-readable format
  • and more small minor features...

Update

See the answer here if you just need a workaround without external library https://stackoverflow.com/a/53546417/6432698

like image 47
billyjov Avatar answered Oct 22 '22 23:10

billyjov


I would suggest you to checkout @angular-material-components/file-input.

It is very Angular Material Compliant.

enter image description here

like image 6
hqho Avatar answered Oct 22 '22 23:10

hqho