2

I'm working on an Angular project.

When I import several documents I have the message "two documents". nothing problematic. enter image description here

The problem arises when I press the delete button that I created. It allows to empty my list but to display there is always written "two documents"

I wish I had that. like when we get to the page for the first time ("no file selected") :

enter image description here

How could I do to reload this input without reloading the page?

My code :

html :

<div class="form-group">
          <label for="pj">Pièce jointe</label>
          <div fxLayout="row wrap" fxLayoutAlign="start center">
            <input type="file" name="pj" id="pj" (change)="onFileChange($event)" multiple>
            <button type="button" (click)="clearFile()" class="btn btn-link">
              <i class="fas fa-trash fa-lg"></i>
            </button>
          </div>
        </div>

ts :

 clearFile() {
 this.message.files = null;
 }

Thanks

1

2 Answers 2

2

If you use a reactive form, you can just call reset() on the form control.

component.html

<form [formGroup]="form">  
  <input type="file" multiple formControlName="files" />
  <button type="button" (click)="clearFile()">
    Delete
  </button>
</form>

component.ts

form: FormGroup;

ngOnInit() {
  this.form = new FormGroup({
    files: new FormControl('')
  });
}

clearFile() {
  this.form.get('files').reset();
}

DEMO: https://stackblitz.com/edit/angular-huvm38

Sign up to request clarification or add additional context in comments.

Comments

0

you can use ViewChild to access the input in your component. First, you need to add #someValue to your input so you can read it in the component:

<input #myInput type="file" name="pj" id="pj" (change)="onFileChange($event)" multiple>

Then in your component you need to import ViewChild from @angular/core:

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

Then you use ViewChild to access the input from template:

// ng 8 @ViewChild('myInput', {static: false}) myInput: ElementRef;
@ViewChild('myInput') myInput: ElementRef;

Now you can use myInput to reset the selected file because it's a reference to input with #myInput, for example create method reset() that will be called on click event of your button:

reset() {
    console.log(this.myInput.nativeElement.files);
    this.myInput.nativeElement.value = "";
    console.log(this.myInput.nativeElement.files);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.