3

I am working on a angular application, currently to upload a file I am using this :

<label class="btn btn-default">
    <input type="file" (change)="selectFile($event)">
</label>
<button class="btn btn-success" [disabled]="!selectedFiles"
    (click)="upload()">Upload</button>

with methods on my .ts file, it is working well.

I want to upgrade this to material angular components raised button like that right now :

<button mat-raised-button>
    <input type="file" (change)="selectFile($event)">
</button>

<button mat-button disabled [disabled]="!selectedFiles" (click)="upload()">Upload</button>

the disabled button is doing well but the input file part doesnt work , it prints baddly and does not open a file folder search window. any ideas?

Edric
  • 24,639
  • 13
  • 81
  • 91
Logan Wlv
  • 3,274
  • 5
  • 32
  • 54

1 Answers1

13

Won't advise using input field within a button, better you hide the file input and then a button to trigger it. The below example will show a minimal example of it

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}} is for Uploading</h2>
    </div>

    <button mat-raised-button (click)="openInput()">
        Select File to Upload
    </button>

<input id="fileInput" hidden type="file" (change)="fileChange($event.target.files)" >

<button mat-button [disabled]="!ourFile" (click)="upload()">Upload</button>

  `
})
export class App {
  name:string;
  ourFile: File; // hold our file

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  /**
   * this is used to trigger the input
   */ 
  openInput(){ 
    // your can use ElementRef for this later
    document.getElementById("fileInput").click();
  }

  fileChange(files: File[]) {
    if (files.length > 0) {
      this.ourFile = files[0];
    }
  }


   /**
   * this is used to perform the actual upload
   */
   upload() {
    console.log('sending this to server', this.ourFile);
  }


}

Check this plnk

With the above example, you should be able to style your button without distorting HTML semantics

WasiF
  • 26,101
  • 16
  • 120
  • 128
Theophilus Omoregbee
  • 2,463
  • 1
  • 22
  • 33
  • FYI, I don't think this event delegation works on Safari Mobile. https://stackoverflow.com/questions/39243513/click-event-doesnt-work-in-safari-mobile-for-some-html-content – mrshickadance Nov 30 '18 at 18:26