Angular 2에서 입력 태그 파일 유형으로 선택한 파일을 재설정하는 방법은 무엇입니까?


89

이것은 내 입력 태그의 모습입니다.

<input type="file" placeholder="File Name" name="filename" (change)="onChange($event)">
<button>Reset</button>

Angular 2에서 선택한 파일을 재설정하고 싶습니다. 도움을 주시면 감사하겠습니다. 더 자세한 정보가 필요하면 알려주세요.

추신

$event매개 변수 에서 파일 세부 사항을 가져 와서 typescript 변수에 저장할 수 있지만이 변수는 입력 태그에 바인딩되지 않습니다.


재설정이라고 말하면 정확히 무엇을 의미합니까? 당신이 만들 수 plnkr.co 및 사후 어떤 문제를 당신이 직면하고
abhinav

답변:


205

를 사용 ViewChild하여 구성 요소의 입력에 액세스 할 수 있습니다 . 먼저, #someValue컴포넌트에서 읽을 수 있도록 입력 에 추가 해야합니다.

<input #myInput type="file" placeholder="File Name" name="filename" (change)="onChange($event)">

그런 다음 구성 요소는 가져와야 ViewChild에서 @angular/core:

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

그런 다음 ViewChild템플릿에서 입력에 액세스하는 데 사용 합니다.

@ViewChild('myInput')
myInputVariable: ElementRef;

이제를 사용 myInputVariable하여 입력에 대한 참조이므로 선택한 파일을 재설정하는 데 사용할 수 있습니다 ( #myInput예 : reset()호출 될 메서드 생성) .click 버튼 이벤트에서 .

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

첫 번째 console.log는 선택한 파일을 인쇄하고 두 번째 console.logthis.myInputVariable.nativeElement.value = "";입력에서 선택한 파일을 삭제 하기 때문에 빈 배열을 인쇄합니다 . this.myInputVariable.nativeElement.value = "";input의 FileList속성이 readonly 이기 때문에 input의 값을 재설정하는 데 사용해야 하므로 배열에서 항목을 제거하는 것은 불가능합니다. 여기 Plunker 가 작동 합니다 .


2
분명한 값이 충분하다 this.myInputVariable.nativeElement.value = "";/?
Pardeep 자이나교

1
@PardeepJain 예, 이것은 파일 입력에서 선택한 파일을 지 웁니다.
Stefan Svrkota 2017

3
myInputVariable실제로 유형입니다ElementRef
phil294

ID가 동적으로 생성되도록 가변 번호의 "입력 유형 = 파일"이있는 경우 어떻게합니까?
Albert Hendriks

2
각도 8 @ViewChild ( 'delDocModal', {정적 : false}) delDocModal : ElementRef;

17

각도 5

HTML

<input type="file" #inputFile>

<button (click)="reset()">Reset</button>

주형

@ViewChild('inputFile') myInputVariable: ElementRef;

reset() {
    this.myInputVariable.nativeElement.value = '';
}

버튼이 필요하지 않습니다. 변경 이벤트 이후에 리셋 할 수 있으며, 데모 용입니다.


나는이 버전을 사용하고 나를 위해 잘 작동합니다 - 감사 @Admir
user1288395을

14

이를 달성하는 한 가지 방법은 입력을 <form>태그 로 래핑 하고 재설정하는 것입니다.

나는 NgForm또는 FormControl둘 중 하나에 thr 양식을 첨부하는 것을 고려하고 있지 않습니다 .

@Component({
  selector: 'form-component',
  template: `
    <form #form>
      <input type="file" placeholder="File Name" name="filename">
    </form>
    <button (click)="reset()">Reset</button>
`
})
class FormComponent {



  @ViewChild('form') form;


  reset() {
    this.form.nativeElement.reset()
  }
}

https://plnkr.co/edit/Ulqh2l093LV6GlQWKkUA?p=preview


.reset()viewChild에서 메소드를 사용할 수 있습니까?
Pardeep Jain

안녕하세요 Edmar ...이 링크에 대한 질문에 대해 저를 도와 줄 수 있습니까? ... stackoverflow.com/questions/48769015/…
Heena

11

일반적으로 선택한 파일을 캡처 한 후 파일 입력을 재설정합니다. 버튼을 누를 필요가 없습니다 . $event전달하려는 객체에 필요한 모든 것이 있습니다 onChange.

onChange(event) {
  // Get your files
  const files: FileList = event.target.files;

  // Clear the input
  event.srcElement.value = null;
}

다른 워크 플로이지만 OP는 버튼을 누르는 것이 요구 사항이라고 언급하지 않습니다.


1
매우 깨끗합니다! 개인적으로 이것이 받아 들여진 대답이어야한다고 생각합니다.
Mazen Elkashef

3

짧은 버전 Plunker :

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

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" placeholder="File Name" name="filename">
      <button (click)="myInput.value = ''">Reset</button>
  `
})
export class AppComponent {


}

그리고 더 일반적인 경우는 버튼을 사용하지 않고 자동으로 재설정하는 것입니다. Angular Template 문 은 연결 식을 지원하므로 Plunker :

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

@Component({
  selector: 'my-app',
  template: `
      <input #myInput type="file" (change)="onChange(myInput.value, $event); myInput.value = ''" placeholder="File Name" name="filename">
  `
})
export class AppComponent {

  onChange(files, event) {
    alert( files );
    alert( event.target.files[0].name );
  }

}

그리고 가치 변화에 대한 재귀가없는 이유에 대한 흥미로운 링크 입니다.


3

간단하다고 생각합니다. #variable을 사용합니다.

<input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event); variable.value='' ">
<button>Reset</button>

"variable.value = null"옵션도 사용 가능


1

제 경우에는 아래와 같이했습니다.

 <input #fileInput hidden (change)="uploadFile($event.target.files)" type="file" />
 <button mat-button color="warn" (click)="fileInput.value=''; fileInput.click()"> Upload File</button>

component.ts에 ViewChild를 만드는 대신 HTML에서 #fileInput을 사용하여 재설정하고 있습니다. "파일 업로드"버튼을 클릭 할 때마다 먼저 #fileInput을 재설정 한 다음 #fileInput.click()기능 을 트리거 합니다. 재설정에 별도의 버튼이 필요한 경우 클릭시 #fileInput.value=''실행할 수 있습니다.


0

주형:

<input [(ngModel)]="componentField" type="file" (change)="fileChange($event)" placeholder="Upload file">

구성 요소:

fileChange(event) {
        alert(this.torrentFileValue);
        this.torrentFileValue = '';
    }
}

0

ng2-file-upload에 문제가있는 경우

HTML :

<input type="file" name="myfile" ` **#activeFrameinputFile** `ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" />

구성 요소

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';

@ViewChild('`**activeFrameinputFile**`') `**InputFrameVariable**`: ElementRef;

this.frameUploader.onSuccessItem = (item, response, status, headers) => {
    this.`**InputFrameVariable**`.nativeElement.value = '';
   };

0

이 입력 태그를 양식 태그에 추가했습니다.

 <form id="form_data">
  <input  type="file" id="file_data"  name="browse"
  (change)="handleFileInput($event, dataFile, f)"  />
</form>

나는 각진 typescript, 아래 줄을 추가하고 문서 양식에서 양식 ID를 가져 와서 해당 값을 null로 만듭니다.

    for(let i=0; i<document.forms.length;i++){
      if(document.forms[i].length > 0){
             if(document.forms[i][0]['value']){ //document.forms[i][0] = "file_data"
                 document.forms[i][0]['value'] = "";
              }
      }
    }

콘솔에서 document.forms를 인쇄하면 아이디어를 얻을 수 있습니다 ..


0

템플릿 참조 변수를 사용하여 메서드로 보낼 수 있습니다.

HTML

<input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event, variable);">

구성 요소

onChange(event: any, element): void {
    // codes
    element.value = '';
  }

0

나는 아주 간단한 앞치마를 사용하고 있습니다. 파일이 업로드 된 후 * ngIf를 사용하여 입력 컨트롤을 곧 제거합니다. 이는 입력 필드가 dom에서 제거되고 다시 추가되는 원인이되며 결과적으로 새 컨트롤이므로 다음과 같습니다.

showUploader: boolean = true;

async upload($event) {
  await dosomethingwiththefile();
  this.showUploader = false;
  setTimeout(() =>{ this.showUploader = true }, 100);
}
<input type="file" (change)="upload($event)" *ngIf="showUploader">


-1
<input type="file" id="image_control" (change)="validateFile($event)" accept="image/gif, image/jpeg, image/png" />
validateFile(event: any): void {
    const self = this;
    if (event.target.files.length === 1) {
      event.srcElement.value = null;
    }
  }

1
코드에 대한 간단한 설명을 제공하여 작동 방식을 설명 할 수 있습니까?
Jacob Nelson

MDN에 따라 이것은 지원이 부족합니다. 참고로,이 URL 확인 developer.mozilla.org/en-US/docs/Web/API/Event/srcElement @JacobNelson
모하메드 가디
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.