Open In App

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

Last Updated : 28 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




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 = "";
  }
}


Output:

After selecting the file:

After pressing clear button:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads