I have a button which when clicked will popup the file selector as below code:
<button mat-raised-button (click)="inputFile.click()">Choose a file</button>
<input #inputFile type="file" [style.display]="'none'" (change)="onChange($event)">
<label>{{fileUpload.name}}</label>
Then I set the file on onChange() so that the selected filename will display in the tag:
this.fileUpload = event.target.files[0];
However, when the file is large, it seems nothing is happening. The label is blank until the filename shows. Is there a way to put a progress/spinner while waiting for the file to be set?
Sorry I would post this as a question if I could, but I can't just yet, so it's an answer:
I've tried around a bit. If it's ok to have the spinner setting off, as soon as the user clicks the button, there would be the possibility to start the loading on input click event, and cancel the loading in the onChange method.
The problem with the spinner/loader is, that as far as I've found out, canceling the upload dialog does not trigger anything. Hence there is the question what would be the right time to stop the timer in that case?
There is the possibility to register this on a blur event. This approach would assume though, that the user will click somewhere on the page once he closed the upload dialog. Not too sure if that's actually an option for you.
component.ts
fileUpload: any;
loading: boolean;
@ViewChild('inputFile') inputFile;
@ViewChild('buttonElem') buttonElem;
onChange(event: any) {
this.loading = false;
this.fileUpload = event.target.files[0];
}
onBlur() {
if(this.loading && document.activeElement !==
this.buttonElem.nativeElement) {
this.loading = false;
}
}
openDialog() {
this.inputFile.nativeElement.value = '';
this.inputFile.nativeElement.click();
}
template
<div>
<button #buttonElem mat-raised-button (blur)="onBlur()"
(click)="openDialog()">Choose a file</button>
<input #inputFile type="file" [style.display]="'none'" (click)="loading =
true" (change)="onChange($event)">
<label *ngIf="fileUpload">{{fileUpload.name}}</label>
</div>
<div>
Loading: {{loading}}
</div>
Here is a stackblitz: stackblitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With