How to reset selected file with input tag file type in Angular 9?

To reset the selected file with input tag file type, we can implement a method which on invocation will clear the selected file.

Approach:

  • Set the id of your input using ‘#’ to make it readable  inside the component.
  • Now in the component we can use ViewChild directive to read the value of the input from the HTML view.
  • For that, import ViewChild from @angular/core.
import { ViewChild } from '@angular/core';
  • ViewChild allows you to set a reference variable to your input, using that you can clear the value of input.
  • After clearing the value of input using the reference variable, the selected file will be reset.

Example:

We will create a similar scenario, there will be an input field and the task will be to create a button which on click will reset the selected file.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component,ViewChild,ElementRef } from '@angular/core';
  
@Component({
  selector: 'app-root',
  template: `
  <div style="text-align: center;">
  <h1>
    {{title}}
  </h1>
  <input #takeInput type="file" name="filename">
    
  <!--After clicking this button the file should be reset.-->
    
  <button (click)="reset()">Clear</button>
  </div>
  `,
  styleUrls: []
})
export class AppComponent {
  title = 'Tutorial'
  
// ViewChild is used to access the input element.
  
  @ViewChild('takeInput', {static: false})
    
// this InputVar is a reference to our input.
  
  InputVar: ElementRef;
  
  reset() 
  {
    
// We will clear the value of the input 
// field using the reference variable.
  
    this.InputVar.nativeElement.value = "";
  }
}

chevron_right


Output:



After selecting the file:

After pressing clear button:

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.