单击按钮在 AngularJS + TypeScript 中浏览文件

Ana*_*kie 1 html javascript spring angularjs typescript

我有user.component.htmluser.component.ts 我发现的所有示例都是 html 这样<input type="file" /> 我不想使用这种样式。我的 html 文件中有:

<button type="button" class="btn" (click)="openPicture()" Browse </button>
Run Code Online (Sandbox Code Playgroud)

下面是 ts 文件上的函数:

  public openPicture() {
    //for testing
    console.log('button clicked to open picture');

    var picture = browse.the.picture.and.assing.to.this.variable;

    //another test, see on console if picture is read
    console.log('%c       ', 'font-size: 100px; background: {{picture}} no-repeat;');
    // Later display picture variable on html and save to database or do anything desired.
}
Run Code Online (Sandbox Code Playgroud)

我在stackoverflow上找到了一个例子angular/material但我没有这个模块。有没有其他替代方法,而无需安装任何额外的包来解决这个问题?

Dak*_*ota 5

你可以这样实现

<input type="file" style="display: none" #file (change)="fileChange($event)"/>
<button type="button" class="btn" (click)="file.click()"> Browse </button>
Run Code Online (Sandbox Code Playgroud)

.ts

export class AppComponent {
  file: File;

  constructor() {

  }

  fileChange(file) {
    this.file = file.target.files[0];
    console.log(this.file.name);
  }
}
Run Code Online (Sandbox Code Playgroud)