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

前端 未结 13 1893
北恋
北恋 2020-12-12 14:56

This is how my input tag looks like:


13条回答
  •  天命终不由人
    2020-12-12 15:29

    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:

    
    

    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:

    @ViewChild('myInput')
    myInputVariable: ElementRef;
    

    Now you can use myInputVariable 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.myInputVariable.nativeElement.files);
        this.myInputVariable.nativeElement.value = "";
        console.log(this.myInputVariable.nativeElement.files);
    }
    

    First console.log will print the file you selected, second console.log will print an empty array because this.myInputVariable.nativeElement.value = ""; deletes selected file(s) from the input. We have to use this.myInputVariable.nativeElement.value = ""; to reset the value of the input because input's FileList attribute is readonly, so it is impossible to just remove item from array. Here's working Plunker.

提交回复
热议问题