Search code examples
angulartypescriptangular6ng2-file-upload

How to reset file input form after uploading the image in Angular?


We have 2 issues connected with selecting files and uploading it. The first issue is that when you upload an image the file name is still staying in the input. Here is the code.

OnFileSelected(event) {
    const file: File = event[0];

    this.ReadAsBase64(file)
      .then(result => {
        this.selectedFile = result;
      })
      .catch (err => this.error = err);

  }

  Upload() {
    if (this.selectedFile) {
      this.usersService.AddImage(this.selectedFile).subscribe(
        data => {
          this.socket.emit('refresh', {});
          console.log(data);
          this.SettingsForm.reset()
        },
        err => err
      );
    }
  }
  ReadAsBase64(file): Promise<any> {
    const reader = new FileReader();
    const fileValue = new Promise((resolve, reject) => {
      reader.addEventListener('load', () => {
        const result = reader.result;
        if (!result) reject('Cannot read variable');
        if (this.images.length>=4) reject('You can have only 4 images');
        if (result.length * 2  > 2**21) reject('File exceeds the maximum size'); // Note: 2*2**20 = 2**21 
        resolve(reader.result);
      });

      reader.addEventListener('error', event => {
        reject(event);
      });

      reader.readAsDataURL(file);
    });

    return fileValue;
  }

HTML

 <div>
                <div class="form-group">
                    <label for="exampleFormControlFile1">Example file input</label>
                    <input #myInput ng2FileSelect [uploader]="uploader" (onFileSelected)="OnFileSelected($event)" type="file"
                        class="form-control-file" id="exampleFormControlFile1" />
                </div>
                <p *ngIf="error"> {{error}}</p>
                <button (click)="Upload()" type="submit" class=" btn btn-default submit-btn btn-upload ">
                    <i class="material-icons">attachment</i>
                    Upload Image</button>
            </div>

How to reset the form after uploading the image? Also, how can I make the error message shown for 3 seconds for example? If you select the wrong file error stays there all the time even after adding the valid file. We thought about adding

setTimeout(() => {

        }, 3000); // just example
      },

but not sure where to add it? How can I fix these 2 issues?


Solution

  • You can do it like this in your component.ts

    import { ViewChild } from '@angular/core';
    

    Then defining a variable to hold it:

    @ViewChild('myInput')
    myInputVariable: ElementRef;
    

    Then in your function

    Upload() {
        if (this.selectedFile) {
          this.usersService.AddImage(this.selectedFile).subscribe(
            data => {
              this.socket.emit('refresh', {});
              console.log(data);
              this.myInputVariable.nativeElement.value = "";
            },
            err => {
                console.log(err);
            }
          );
        }
      }
    

    To remove the error: OnFileSelected(event) { const file: File = event[0];

    this.ReadAsBase64(file)
      .then(result => {
        this.selectedFile = result;
      })
      .catch (err => {this.error = err; setTimeout(()=> {this.error = ''},2000}));
    

    }