【问题标题】:Clearing select field in angular以角度清除选择字段
【发布时间】:2018-11-30 00:19:56
【问题描述】:

如何分别清除这些字段?

<div class="form-group">
    <label for="lrcfile">Lyrics file (.lrc)</label>
    <input type="file" class="form-control-file" id="lrcfile" accept=".lrc" (change)="setLrcFile($event)" >
</div>
<div class="form-group">
    <label for="pitchfile">Pitches file (.txt)</label>
    <input type="file" class="form-control-file" id="pitchfile" accept=".txt" (change)="setPitchfile($event)">
</div>

lrcfile: any;
pitchfile: any;

设置文件:

setPitchfile(fileInput: any) {
    for (var i =  fileInput.target.files.length - 1; i >= 0; i--) {
         var file = fileInput.target.files[i];
         this.pitchfile = file;
    }
}

像大多数消息来源推荐的那样,将它们设置为 ' 'null 不会做任何事情。

this.pitchfile = null;

它仍然显示它在那里。在这张图片中,您可以看到我之前选择的 lrc 文件保持原样,并且我没有对 txt 文件进行任何更改,只是为了展示它的外观。

编辑

我确实设法清除了它,但清除的有点太多了。这样我可以清除我所有的 &lt;input&gt; 字段,但我只想要带有 type = "file" 的字段。

在我的HTML 我还有其他&lt;input&gt;'s 喜欢..

<div class="form-group">
  <label for="durationText">Song Duration (ms)</label>
  <input type="text" class="form-control" [(ngModel)]="durationText" id="durationText" placeholder="Song Duration">
</div>

哪些不是type = "file"。我设法使用jquery 清除了它们。

jQuery('#addNewSongDialog').find("input,textarea,select")
        .val('')
        .end()

有没有办法使用它来只清除type = "file" 字段?

【问题讨论】:

  • “未选择文件”...嗯,我看不到了。
  • @BenSteward 我只是在展示它是如何保持的以及它应该是什么样子。将编辑帖子。
  • @BenSteward 所以没有办法清除它?
  • 我不知道我停止阅读了。不过,您应该继续阅读。

标签: angular select


【解决方案1】:

好的,下面是一些适合我的代码:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>
  <div class="form-group">
    <label for="lrcfile">Lyrics file (.lrc)</label>
    <input type="file" class="form-control-file" id="lrcfile" accept=".lrc" (change)="setLrcFile($event)" >
</div>
<div class="form-group">
    <label for="pitchfile">Pitches file (.txt)</label>
    <input type="file" class="form-control-file" id="pitchfile" accept=".txt" #file (change)="setPitchfile($event)">
</div>
<button (click)="clear(file)">Clear Pitches</button>
`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  @Input() name: string;
  pitchfile = '';

  constructor() {
  }

  clear(file) {
    file.value = '';
  }

  setPitchfile(fileInput: any) {
    for (var i = fileInput.target.files.length - 1; i >= 0; i--) {
      var file = fileInput.target.files[i];
      this.pitchfile = file;
    }
  }
}

相关的 stackblitz 在这里:https://stackblitz.com/edit/angular-swrvew

在这一行:

    <input type="file" class="form-control-file" 
           id="pitchfile" accept=".txt" 
           #file (change)="setPitchfile($event)">

我添加了一个模板引用变量(#file),它提供了对控件的引用。

在 Clear 按钮上,我将它传递给 clear 方法。然后我使用控件的value 属性来清除文本。

这有帮助吗?

【讨论】:

  • Wierd.. 当我尝试 file.value = ''; 时它不起作用,但现在它以某种方式起作用。无论如何,非常感谢您的帮助。它现在正在工作。
猜你喜欢
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 2020-03-06
相关资源
最近更新 更多