【问题标题】:Angular 4/5 material raised button with input file带输入文件的 Angular 4/5 材质凸起按钮
【发布时间】:2018-02-02 08:51:11
【问题描述】:

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

<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>

禁用的按钮运行良好,但输入文件部分不起作用,它打印不好并且没有打开文件夹搜索窗口。有什么想法吗?

【问题讨论】:

  • 你不能在一个按钮上放置一个文件类型的输入,而是创建一个按钮来欺骗输入文件,让我通过回答来举个例子

标签: html angular angular-material


【解决方案1】:

不建议在按钮中使用输入字段,最好隐藏文件输入,然后使用按钮触发它。下面的示例将显示它的一个最小示例

@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 语义的情况下设置按钮样式

【讨论】:

猜你喜欢
  • 2017-05-10
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多