Reputation: 171
How can I separately clear these fields?
<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;
Setting the file:
setPitchfile(fileInput: any) {
for (var i = fileInput.target.files.length - 1; i >= 0; i--) {
var file = fileInput.target.files[i];
this.pitchfile = file;
}
}
Setting them to ' '
or to null
like most sources recommend does not do anything.
this.pitchfile = null;
It still shows like it is there. In this picture you can see that the lrc
file that I had chosen before stays like it was and I have not made any changes to the txt
file just to show how it should look like.
EDIT
I did manage to clear it, but it clears a bit too much.. with this I could clear all of my <input>
fields, but I only want the ones with the type = "file"
.
In my HTML
I have other <input>'s
like..
<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>
Which are not type = "file"
. I managed to clear them all using jquery
.
jQuery('#addNewSongDialog').find("input,textarea,select")
.val('')
.end()
Is there maybe a way to use this to only clear type = "file"
fields?
Upvotes: 1
Views: 71
Reputation: 60596
OK, here is some code that works for me:
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;
}
}
}
The associated stackblitz is here: https://stackblitz.com/edit/angular-swrvew
On this line:
<input type="file" class="form-control-file"
id="pitchfile" accept=".txt"
#file (change)="setPitchfile($event)">
I added a template reference variable (#file) that provides a reference to the control.
On the Clear button, I pass that along to the clear method. I then use the value
property of the control to clear the text.
Does that help?
Upvotes: 2