0

I'm new to angular, I'm trying to display list of labels with remove button, when selecting file from folder using input type=“file” using below code,

 <input #fileInput type="file"  />
<button type="button" (click)="fileInput.click()">trigger</button>

And I want to remove the added file name from that list by clicking remove button in that corresponding row using ngFor option. Can anyone suggest me an idea to achieve this? Thanks in advance.

2 Answers 2

1

In ts file

    files = [];

    onFileChange(event) {
        if (event.target.files && event.target.files.length > 0) {
            this.selectedFile = event.target.files[0];
            this.files.push(this.selectedFile);
        }
    }

    removeFile(index) {
           this.files.splice(i, 1);
    }

In html file

    <input #fileInput type="file" (change)="onFileChange($event)"/> 
    <button type="button" (click)="fileInput.click()">trigger</button>

    <div *ngFor="let file of files;let i = index;">
      {{file.name}} <span (click)="removeFile(i)"> Remove</span>
    </div>
Sign up to request clarification or add additional context in comments.

Comments

0

Just pass the corresponding element in your remove function and remove value of that input field, like below -

<div *ngFor='let item of list; let i = index'>
  <input #fileInput type="file"  />
  <button type="button" (click)="fileInput.click()">trigger</button>
  <button type="button" (click)="reset(fileInput, i)">Reset</button>
</div>


reset(element, index) {
    console.log(element);
    element.value = "";
  }

Working Example

1 Comment

sorry its not working. I have placed input field and trigger button outside the div tag. Its replacing the current file and its not listing the selected file.

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.