带有输入文件的Angular 4/5材料凸起按钮

时间:2018-02-02 08:51:12

标签: html angular angular-material material

我正在开发一个角度应用程序,目前正在上传我正在使用的文件:

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

使用.ts文件中的方法,它运行良好。

我想立即将其升级为材质角度组件凸起按钮:

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

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

禁用按钮运行良好,但输入文件部分不起作用,打印效果不佳,无法打开文件夹搜索窗口。任何想法?

1 个答案:

答案 0 :(得分:11)

不建议使用按钮内的输入字段,更好地隐藏文件输入,然后按一下按钮来触发它。以下示例将显示它的最小示例

@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);
  }


}

选中此plnk

通过上面的示例,您应该能够设置按钮的样式而不会扭曲HTML语义